GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Performance & diagnostics best practices - call for ideas · Issue #256 · goldbergyoni/nodebestpractices

Performance & diagnostics best practices - call for ideas #256

New issue
Copy link
New issue
Copy link
Closed
Closed
Performance & diagnostics best practices - call for ideas#256
Copy link
Labels
new best practiceperformancestalewriter-needed

Description

@goldbergyoni
goldbergyoni
opened on Sep 26, 2018
Issue body actions

We'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

Activity

Next
  1. goldbergyoni
    added
    new best practice
    writer-needed
    performance
    on Sep 26, 2018
  2. goldbergyoni commented on Sep 26, 2018

    @goldbergyoni
    goldbergyoni
    on Sep 26, 2018
    OwnerAuthor
    More actions

    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
  3. profnandaa commented on Sep 26, 2018

    @profnandaa
    profnandaa
    on Sep 26, 2018
    More actions

    Perhaps debugging can be part of it? This is a good place - https://www.joyent.com/node-js/production/debug

    Reacted by Yoni Goldberg and Sagir Khan
  4. js-kyle commented on Sep 27, 2018

    @js-kyle
    js-kyle
    on Sep 27, 2018
    Contributor
    More actions

    The express documentation has good tips: https://expressjs.com/en/advanced/best-practice-performance.html

    We may want to review the current production practices section, as they may overlap or be more appropriate as part of the new section, for example the bullet around serving assets from a CDN rather than Node.js

    Reacted by Sagir Khan, Bruno Scheufler, Yoni Goldberg and Tommy Byrd
  5. sagirk commented on Sep 27, 2018

    @sagirk
    sagirk
    on Sep 27, 2018
    Contributor
    More actions

    Choose the classical for loop over forEach/ES6 of when dealing with huge amounts of data (e.g., 10/100 million+).

    Reasons why:
    https://medium.com/tech-tajawal/loops-performances-in-node-js-9fbccf2d6aa6

    https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea

    https://stackoverflow.com/questions/43031988/javascript-efficiency-for-vs-foreach/43032526#43032526

    https://stackoverflow.com/questions/3520688/javascript-loop-performance-why-is-to-decrement-the-iterator-toward-0-faster-t

    Reacted by Yoni Goldberg and Bruno Scheufler
  6. sagirk commented on Sep 27, 2018

    @sagirk
    sagirk
    on Sep 27, 2018
    Contributor
    More actions

    Use a version of node that ships with new TurboFan JIT compiler rather than just the older Crankshaft compiler.

    Reasons why:
    https://medium.com/the-node-js-collection/get-ready-a-new-v8-is-coming-node-js-performance-is-changing-46a63d6da4de

    Reacted by Kyle Martin, Yoni Goldberg, Bruno Scheufler and Poorshad Shaddel
  7. AbdelrahmanHafez commented on Sep 27, 2018

    @AbdelrahmanHafez
    AbdelrahmanHafez
    on Sep 27, 2018
    Contributor
    More actions

    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
  8. goldbergyoni commented on Sep 27, 2018

    @goldbergyoni
    goldbergyoni
    on Sep 27, 2018
    OwnerAuthor
    More actions

    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"

    Reacted by Sagir Khan
  9. goldbergyoni commented on Sep 27, 2018

    @goldbergyoni
    goldbergyoni
    on Sep 27, 2018
    OwnerAuthor
    More actions

    Use factories or constructors to ensure objects are created using the same schema so the v8 won't have to generate hidden classes on runtime (a.k.a POLYMORPHIC VS MONOMORPHIC FUNCTIONS)

    https://medium.com/the-node-js-collection/get-ready-a-new-v8-is-coming-node-js-performance-is-changing-46a63d6da4de

    Reacted by Sagir Khan and Ahmad Alkhous
  10. VinayaSathyanarayana commented on Oct 1, 2018

    @VinayaSathyanarayana
    VinayaSathyanarayana
    on Oct 1, 2018
    Contributor
    More actions
    • Analyze repeated API Calls/Database Queries to cache them.
    • Debounce and Throttle : https://css-tricks.com/debouncing-throttling-explained-examples/
    Reacted by Yoni Goldberg, Sagir Khan and lsmialowskiPGS
  11. goldbergyoni commented on Oct 2, 2018

    @goldbergyoni
    goldbergyoni
    on Oct 2, 2018
    OwnerAuthor
    More actions

    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
  12. TheHollidayInn commented on Oct 5, 2018

    @TheHollidayInn
    TheHollidayInn
    on Oct 5, 2018
    Contributor
    More actions

    Analyzing and monitoring cpu bottlenecks or memory leaks with Node Clinic/Prometheus

    • https://clinicjs.org/
    • https://blog.risingstack.com/node-js-performance-monitoring-with-prometheus/
    Reacted by Yoni Goldberg and Sagir Khan
  13. TheHollidayInn commented on Oct 7, 2018

    @TheHollidayInn
    TheHollidayInn
    on Oct 7, 2018
    Contributor
    More actions

    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:

    • https://medium.com/skyshidigital/6-tricks-to-speed-up-and-improve-your-node-js-performance-fadc06d15cbe
    • https://www.sitepoint.com/10-tips-make-node-js-web-app-faster/
    • https://medium.com/node-and-beyond/the-incomplete-collection-of-node-js-performance-tips-94cc712661bd
    • https://ifelse.io/2016/02/23/using-node-redis-and-kue-for-priority-job-processing/
    Reacted by Bruno Barreto Carvalho, Kyle Martin and Sagir Khan
  14. 36 remaining items

  15. migramcastillo commented on Mar 19, 2019

    @migramcastillo
    migramcastillo
    on Mar 19, 2019
    More actions

    @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?

  16. sagirk commented on Mar 21, 2019

    @sagirk
    sagirk
    on Mar 21, 2019
    Contributor
    More actions

    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.

    Reacted by Yoni Goldberg
  17. stale commented on Jun 19, 2019

    @stale
    staleBot
    on Jun 19, 2019
    More actions

    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! 💚

  18. stale
    added
    stale
    on Jun 19, 2019
  19. stale
    closed this as completedon Jun 29, 2019
  20. abhishekshetty commented on Apr 10, 2020

    @abhishekshetty
    abhishekshetty
    on Apr 10, 2020
    More actions
    * 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

  21. abhishekshetty commented on Apr 10, 2020

    @abhishekshetty
    abhishekshetty
    on Apr 10, 2020
    More actions
    1. 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.

    2. 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
  22. victor-homyakov commented on Oct 12, 2020

    @victor-homyakov
    victor-homyakov
    on Oct 12, 2020
    Contributor
    More actions

    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:

    • Fix slow autoprefixer calls in *-no-vendor-prefix stylelint/stylelint#4971 - import of 3rd-party modules in stylelint may take about 1.8 seconds
    • Performance: plugin adds 150-200ms to ESLint startup time because of ramda lo1tuma/eslint-plugin-mocha#213 - import of ramda adds 150-200ms to ESLint startup time

    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)
  23. Aschen commented on Jan 6, 2021

    @Aschen
    Aschen
    on Jan 6, 2021
    More actions

    Reduce hidden classes number

    Benefits from the inline cache and let Turbofan generate optimized assembly code

    Use the ES Lint sort-keys rule to ensure same internal hidden classes for your object.

    This will allows to fully benefits from the inline caching. Also Turbofan will be able to compile the JS code into optimized bytecode.

    If you are interested I can write a section on this topic, providing code example, performance diff, etc

    Hidden classes and Inline cache
    Inline Caches with Monomorphism, Polymorphism and Megamorphism
    Interpreter and Compiler: hidden classes, inline caching, polymorphism and megamorphism
    Turbofan Speculative Optimization

  24. Aschen commented on Jan 6, 2021

    @Aschen
    Aschen
    on Jan 6, 2021
    More actions

    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

  25. Aschen commented on Jan 6, 2021

    @Aschen
    Aschen
    on Jan 6, 2021
    More actions

    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

  26. kibertoad commented on Jan 6, 2021

    @kibertoad
    kibertoad
    on Jan 6, 2021
    More actions

    Avoid process.env. Copy and cache it: https://www.reddit.com/r/node/comments/7thtlv/performance_penalty_of_accessing_env_variables/
    The whole concept of object shapes: https://mathiasbynens.be/notes/shapes-ics (previously mentioned in the context of monomorphic params, but it's also important in the context of initializing variables)
    Avoid using express.js (it is really, really slow: https://github.com/fastify/benchmarks)

    Reacted by Manuel Spigolon and Maksym Shenderuk
  27. Aschen commented on Jan 10, 2021

    @Aschen
    Aschen
    on Jan 10, 2021
    More actions

    @goldbergyoni Are you still looking for contributor on this topic?

  28. rluvaton commented on Mar 24, 2022

    @rluvaton
    rluvaton
    on Mar 24, 2022
    Collaborator
    More actions

    There are really good ideas here! We should add it

    I also have some:

    1. 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)
    2. 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
    
    }
    
    1. Read large files in streams instead all at once
  29. victor-homyakov commented on Mar 31, 2022

    @victor-homyakov
    victor-homyakov
    on Mar 31, 2022
    Contributor
    More actions
    1. 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.

    1. 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)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    new best practiceperformancestalewriter-needed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402792 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.