SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Startup Snapshot in
Node.js
Joyee Cheung, 14 May 2023
About me
● Compilers @ Igalia
● Node.js TSC member & V8 committer
● Been working on startup performance → startup snapshot strategic initiative
Challenge of Node.js core startup
● Node.js is growing: increasing number of
○ Globals (in particular Web APIs)
○ Built-in modules and new APIs in existing modules
○ …and generally “things to do to make new things work”: set up handlers, define accessors…
● In v18-v20:
○ Fetch
○ WebCrypto
○ File API, Blob
○ Web streams: globalThis.ReadableStream, globalThis.CompressionStream…
○ util.parseArgs, util.MIMEType...
Challenge of Node.js core startup
● The Node.js core is roughly half in JavaScript, half in C++ (and some others)
● Pros
○ Lower the contribution barrier
○ Reduce some C++ → JavaScript callback costs
● Cons
○ Need to parse and compile JavaScript
○ Overall initialization speed is affected - JS code that only gets run once don’t get optimized
○ Need to defend against prototype pollution and monkey patching: copying JS built-ins at
startup to avoid blowups caused by e.g. delete String.prototype.startsWith
Trying to keep the startup under control
1. Lazy loading: do not load non-essential features until it’s actually used
○ e.g. crypto, performance timing, messaging
2. Code cache: when loading additional features (built-in modules)
○ Bytecode and metadata etc.
○ Compiled and embedded into the executable at build time.
○ Skips compilation when validation passes.
3. V8 startup snapshot: pre-initialize features that are almost always loaded /
essential initializations
○ URL, fs, etc…used by other internals
○ Buffer, setTimeout, etc.: widely used
○ Skips execution of the initialization code
Startup snapshots within Node.js core
Internal JS in source
Embed into
executable
Internal JS
node executable
BUILD TIME RUN TIME
Raw bootstrap code
Compiled bootstrap code
Initialized Node.js core
Parse, compile
Execute
Initialized user app
Process user input,
system states
Internal JS
node executable
BUILD TIME RUN TIME
Raw bootstrap code
Compiled bootstrap code
Initialized Node.js core
Parse, compile
Execute
Initialized user app
Process user input,
system states
Startup snapshots within Node.js core
Internal JS
Compiled code
Pre-compile
Embed into
executable
Code cache
Internal JS
node executable
BUILD TIME RUN TIME
Raw bootstrap code
Compiled bootstrap code
Initialized Node.js core
Parse, compile
Execute
Initialized user app
Process user input,
system states
Code cache
Startup snapshots within Node.js core
Internal JS + Native
Embed into
executable
Snapshot
Initialized Node.js heap
Parse, compile,
execute
Snapshot
Serialize
What are V8 startup snapshots?
● V8 heap states serialized into a binary blob
● Isolate snapshot: shared by main instance and workers
○ Primitives: strings, symbols, etc.
○ Native bindings
● Context snapshot: main context, vm contexts, worker context (minimal)
○ Execution context
○ Globals
○ Objects
○ Functions
Startup snapshots within Node.js core
● The default startup (with snapshot) is generally 2x faster than startup with --
no-node-snapshot: ~40ms -> ~20ms
● A sustainable path for growing core & keeping startup under control
User-land startup snapshots
Creating snapshots from user application code, useful if
● Startup performance matters e.g. in CLI tools
● A lot of code needs to be compiled/run during startup
● A lot of system-independent data needs to be loaded during startup
User-land startup snapshots
● Currently requires the snapshot script to be a one-file bundle
○ User-land module support is WIP
● Run-to-completion: until async operations are finished, promises are resolved
User JS script
Initialized user heap
Parse, compile, execute
Snapshot
Serialize
Initialized user heap
User app
Process additional
input, system states
node
executable
Deserialize
User-land startup snapshots
Build-time generation, embedded binary: from v17.9.0
● Building Node.js from source and embedding the snapshot into the binary
$ echo 'globalThis.data = "hello"' > snapshot.js
$ cd /path/to/node
$ ./configure --node-snapshot-main=snapshot.js && make node
$ out/Release/node # globalThis.data contains "hello"
User-land startup snapshots
Run-time generation, separate binary: from v18.8.0
● Use the default Node.js binary to write snapshot to a separate blob for
loading later
$ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js
$ node --snapshot-blob snapshot.blob # deserialize snapshot
User-land startup snapshots
Runtime generation, embedded binary: in v20.?
● Layer on top of single-executable application (work in progress)
● Use the default Node.js binary to generate a blob which includes the snapshot
(and more), and inject it into one single executable
● No need to compile Node.js from source
● A single-line utility command to come
$ echo '{"snapshot_main":"sea.js","output":"sea.blob"}' > sea.json
$ node --experimental-sea-config sea.json
$ cp node sea
$ npx postject sea NODE_SEA_BLOB sea.blob --sentinel-fuse 
$NODE_SEA_FUSE
$ ./sea # contains snapshot
JS API: Synchronizing run-time states
● Node.js refreshes process.env and process.argv etc. when the
snapshot is deserialized
● States computed from system states can be synchronized during
deserialization.
let debug_level = 0;
function computeDebugLevel() {
switch (process.env.DEBUG_LEVEL) {
case 'none': debug_level = 0; break;
case 'debug': debug_level = 1; break;
}
}
JS API: Synchronizing run-time states
const {
addSerializeCallback, addDeserializeCallback, isBuildingSnapshot
} = require(‘v8’).startupSnapshot;
// Usual startup
computeDebugLevel();
// Snapshot synchronization
if (isBuildingSnapshot()) {
addSerializeCallback(() => { debug_level = 0; /* reset */ })
addDeserializeCallback(computeDebugLevel); /* re-compute */
}
// Or, defer the computation until deserialization if building snapshot
if (!isBuildingSnapshot()) { computeDebugLevel(); }
else { addDeserializeCallback(computeDebugLevel); }
JS API: configure main function
// In the snapshot:
const greetings = { en_US: 'hello', zh_CN: '你好', es_ES: 'hola' };
2. Configure the main function in the same snapshot script
$ echo "console.log(greetings[process.env.LANGUAGE])" > hello.js
$ LANGUAGE=en_US node --snapshot-blob snapshot.blob hello.js # logs "hello"
1. Pass a separate main script that does the logging
$ LANGUAGE=en_US node --snapshot-blob snapshot.blob # logs "hello"
require('v8').startupSnapshot.setDeserializeMainFunction(() => {
console.log(greetings[process.env.LANGUAGE]);
});
Summary
● Startup snapshot has been integrated into Node.js core to speed up core
startup
● Experimental user-land snapshot support is now available, with JS APIs in
v8.startupSnapshot
● Support for single executable applications and more features is WIP
Thanks
● @addaleax, @cjihrig, @jasnel, @legendecas, @RaisinTen, et al.
● Bloomberg & Igalia

Weitere ähnliche Inhalte

Was ist angesagt?

B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]
B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]
B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]
日本マイクロソフト株式会社
 

Was ist angesagt? (20)

オープンデータ・プラットフォーム KYOTO OPEN DATA
オープンデータ・プラットフォーム KYOTO OPEN DATAオープンデータ・プラットフォーム KYOTO OPEN DATA
オープンデータ・プラットフォーム KYOTO OPEN DATA
 
Computing Performance: On the Horizon (2021)
Computing Performance: On the Horizon (2021)Computing Performance: On the Horizon (2021)
Computing Performance: On the Horizon (2021)
 
MLflowで学ぶMLOpsことはじめ
MLflowで学ぶMLOpsことはじめMLflowで学ぶMLOpsことはじめ
MLflowで学ぶMLOpsことはじめ
 
NVIDIA cuQuantum SDK による量子回路シミュレーターの高速化
NVIDIA cuQuantum SDK による量子回路シミュレーターの高速化NVIDIA cuQuantum SDK による量子回路シミュレーターの高速化
NVIDIA cuQuantum SDK による量子回路シミュレーターの高速化
 
공공데이터 활용사례
공공데이터 활용사례공공데이터 활용사례
공공데이터 활용사례
 
ラズパイでデバイスドライバを作ってみた。
ラズパイでデバイスドライバを作ってみた。ラズパイでデバイスドライバを作ってみた。
ラズパイでデバイスドライバを作ってみた。
 
Ethics of AI - AIの倫理-
Ethics of AI - AIの倫理-Ethics of AI - AIの倫理-
Ethics of AI - AIの倫理-
 
JANOG43 Forefront of SRv6, Open Source Implementations
JANOG43 Forefront of SRv6, Open Source ImplementationsJANOG43 Forefront of SRv6, Open Source Implementations
JANOG43 Forefront of SRv6, Open Source Implementations
 
NEDO特別講座 ロボット共通プラットフォーム講習会 (1)
NEDO特別講座 ロボット共通プラットフォーム講習会 (1)NEDO特別講座 ロボット共通プラットフォーム講習会 (1)
NEDO特別講座 ロボット共通プラットフォーム講習会 (1)
 
Telemetry事始め
Telemetry事始めTelemetry事始め
Telemetry事始め
 
B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]
B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]
B07_業務の自動化を多角的に実現する Power Automate の世界 [Microsoft Japan Digital Days]
 
Q4.11: Using GCC Auto-Vectorizer
Q4.11: Using GCC Auto-VectorizerQ4.11: Using GCC Auto-Vectorizer
Q4.11: Using GCC Auto-Vectorizer
 
OpenStreetMap 기반의 위치데이터서비스 플랫폼 - Mapbox
OpenStreetMap 기반의 위치데이터서비스 플랫폼 - MapboxOpenStreetMap 기반의 위치데이터서비스 플랫폼 - Mapbox
OpenStreetMap 기반의 위치데이터서비스 플랫폼 - Mapbox
 
Open Policy Agent (OPA) 入門
Open Policy Agent (OPA) 入門Open Policy Agent (OPA) 入門
Open Policy Agent (OPA) 入門
 
サーバサイドの並行プログラミング〜かんたんマルチスレッドプログラミング〜
サーバサイドの並行プログラミング〜かんたんマルチスレッドプログラミング〜サーバサイドの並行プログラミング〜かんたんマルチスレッドプログラミング〜
サーバサイドの並行プログラミング〜かんたんマルチスレッドプログラミング〜
 
フィルタドライバ入門
フィルタドライバ入門フィルタドライバ入門
フィルタドライバ入門
 
Openflow実験
Openflow実験Openflow実験
Openflow実験
 
世界と日本のDNSSEC
世界と日本のDNSSEC世界と日本のDNSSEC
世界と日本のDNSSEC
 
FIWARE Big Data Ecosystem : Cygnus and STH Comet
FIWARE Big Data Ecosystem : Cygnus and STH CometFIWARE Big Data Ecosystem : Cygnus and STH Comet
FIWARE Big Data Ecosystem : Cygnus and STH Comet
 
TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
TEE (Trusted Execution Environment)は第二の仮想化技術になるか?TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
 

Ähnlich wie Startup Snapshot in Node.js

Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
Edureka!
 

Ähnlich wie Startup Snapshot in Node.js (20)

Nodejs
NodejsNodejs
Nodejs
 
OSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshopOSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshop
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Treinamento frontend
Treinamento frontendTreinamento frontend
Treinamento frontend
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.js
 
Nodejs web service for starters
Nodejs web service for startersNodejs web service for starters
Nodejs web service for starters
 
Modern Development Tools
Modern Development ToolsModern Development Tools
Modern Development Tools
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Node js
Node jsNode js
Node js
 
Intro to SpringBatch NoSQL 2021
Intro to SpringBatch NoSQL 2021Intro to SpringBatch NoSQL 2021
Intro to SpringBatch NoSQL 2021
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
 
Capistrano deploy Magento project in an efficient way
Capistrano deploy Magento project in an efficient wayCapistrano deploy Magento project in an efficient way
Capistrano deploy Magento project in an efficient way
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Making your app soar without a container manifest
Making your app soar without a container manifestMaking your app soar without a container manifest
Making your app soar without a container manifest
 
GeoServer Developers Workshop
GeoServer Developers WorkshopGeoServer Developers Workshop
GeoServer Developers Workshop
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue Solutions
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
SenchaCon 2016: Develop, Test & Deploy with Docker - Jonas Schwabe
 
Grunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous IntegrationGrunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous Integration
 

Mehr von Igalia

Building End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPEBuilding End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPE
Igalia
 
Automated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded DevicesAutomated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded Devices
Igalia
 
Running JS via WASM faster with JIT
Running JS via WASM      faster with JITRunning JS via WASM      faster with JIT
Running JS via WASM faster with JIT
Igalia
 
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por IgaliaIntroducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Igalia
 

Mehr von Igalia (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Building End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPEBuilding End-user Applications on Embedded Devices with WPE
Building End-user Applications on Embedded Devices with WPE
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded DevicesAutomated Testing for Web-based Systems on Embedded Devices
Automated Testing for Web-based Systems on Embedded Devices
 
Embedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to MaintenanceEmbedding WPE WebKit - from Bring-up to Maintenance
Embedding WPE WebKit - from Bring-up to Maintenance
 
Optimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdfOptimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdf
 
Running JS via WASM faster with JIT
Running JS via WASM      faster with JITRunning JS via WASM      faster with JIT
Running JS via WASM faster with JIT
 
To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!To crash or not to crash: if you do, at least recover fast!
To crash or not to crash: if you do, at least recover fast!
 
Implementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamerImplementing a Vulkan Video Encoder From Mesa to GStreamer
Implementing a Vulkan Video Encoder From Mesa to GStreamer
 
8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in Mesa8 Years of Open Drivers, including the State of Vulkan in Mesa
8 Years of Open Drivers, including the State of Vulkan in Mesa
 
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por IgaliaIntroducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
Introducción a Mesa. Caso específico dos dispositivos Raspberry Pi por Igalia
 
2023 in Chimera Linux
2023 in Chimera                    Linux2023 in Chimera                    Linux
2023 in Chimera Linux
 
Building a Linux distro with LLVM
Building a Linux distro        with LLVMBuilding a Linux distro        with LLVM
Building a Linux distro with LLVM
 
turnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUsturnip: Update on Open Source Vulkan Driver for Adreno GPUs
turnip: Update on Open Source Vulkan Driver for Adreno GPUs
 
Graphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devicesGraphics stack updates for Raspberry Pi devices
Graphics stack updates for Raspberry Pi devices
 
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOSDelegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
Delegated Compositing - Utilizing Wayland Protocols for Chromium on ChromeOS
 
MessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the webMessageFormat: The future of i18n on the web
MessageFormat: The future of i18n on the web
 
Replacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shadersReplacing the geometry pipeline with mesh shaders
Replacing the geometry pipeline with mesh shaders
 
I'm not an AMD expert, but...
I'm not an AMD expert, but...I'm not an AMD expert, but...
I'm not an AMD expert, but...
 
Status of Vulkan on Raspberry
Status of Vulkan on RaspberryStatus of Vulkan on Raspberry
Status of Vulkan on Raspberry
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 

Kürzlich hochgeladen (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

Startup Snapshot in Node.js

  • 1. Startup Snapshot in Node.js Joyee Cheung, 14 May 2023
  • 2. About me ● Compilers @ Igalia ● Node.js TSC member & V8 committer ● Been working on startup performance → startup snapshot strategic initiative
  • 3. Challenge of Node.js core startup ● Node.js is growing: increasing number of ○ Globals (in particular Web APIs) ○ Built-in modules and new APIs in existing modules ○ …and generally “things to do to make new things work”: set up handlers, define accessors… ● In v18-v20: ○ Fetch ○ WebCrypto ○ File API, Blob ○ Web streams: globalThis.ReadableStream, globalThis.CompressionStream… ○ util.parseArgs, util.MIMEType...
  • 4. Challenge of Node.js core startup ● The Node.js core is roughly half in JavaScript, half in C++ (and some others) ● Pros ○ Lower the contribution barrier ○ Reduce some C++ → JavaScript callback costs ● Cons ○ Need to parse and compile JavaScript ○ Overall initialization speed is affected - JS code that only gets run once don’t get optimized ○ Need to defend against prototype pollution and monkey patching: copying JS built-ins at startup to avoid blowups caused by e.g. delete String.prototype.startsWith
  • 5. Trying to keep the startup under control 1. Lazy loading: do not load non-essential features until it’s actually used ○ e.g. crypto, performance timing, messaging 2. Code cache: when loading additional features (built-in modules) ○ Bytecode and metadata etc. ○ Compiled and embedded into the executable at build time. ○ Skips compilation when validation passes. 3. V8 startup snapshot: pre-initialize features that are almost always loaded / essential initializations ○ URL, fs, etc…used by other internals ○ Buffer, setTimeout, etc.: widely used ○ Skips execution of the initialization code
  • 6. Startup snapshots within Node.js core Internal JS in source Embed into executable Internal JS node executable BUILD TIME RUN TIME Raw bootstrap code Compiled bootstrap code Initialized Node.js core Parse, compile Execute Initialized user app Process user input, system states
  • 7. Internal JS node executable BUILD TIME RUN TIME Raw bootstrap code Compiled bootstrap code Initialized Node.js core Parse, compile Execute Initialized user app Process user input, system states Startup snapshots within Node.js core Internal JS Compiled code Pre-compile Embed into executable Code cache
  • 8. Internal JS node executable BUILD TIME RUN TIME Raw bootstrap code Compiled bootstrap code Initialized Node.js core Parse, compile Execute Initialized user app Process user input, system states Code cache Startup snapshots within Node.js core Internal JS + Native Embed into executable Snapshot Initialized Node.js heap Parse, compile, execute Snapshot Serialize
  • 9. What are V8 startup snapshots? ● V8 heap states serialized into a binary blob ● Isolate snapshot: shared by main instance and workers ○ Primitives: strings, symbols, etc. ○ Native bindings ● Context snapshot: main context, vm contexts, worker context (minimal) ○ Execution context ○ Globals ○ Objects ○ Functions
  • 10. Startup snapshots within Node.js core ● The default startup (with snapshot) is generally 2x faster than startup with -- no-node-snapshot: ~40ms -> ~20ms ● A sustainable path for growing core & keeping startup under control
  • 11. User-land startup snapshots Creating snapshots from user application code, useful if ● Startup performance matters e.g. in CLI tools ● A lot of code needs to be compiled/run during startup ● A lot of system-independent data needs to be loaded during startup
  • 12. User-land startup snapshots ● Currently requires the snapshot script to be a one-file bundle ○ User-land module support is WIP ● Run-to-completion: until async operations are finished, promises are resolved User JS script Initialized user heap Parse, compile, execute Snapshot Serialize Initialized user heap User app Process additional input, system states node executable Deserialize
  • 13. User-land startup snapshots Build-time generation, embedded binary: from v17.9.0 ● Building Node.js from source and embedding the snapshot into the binary $ echo 'globalThis.data = "hello"' > snapshot.js $ cd /path/to/node $ ./configure --node-snapshot-main=snapshot.js && make node $ out/Release/node # globalThis.data contains "hello"
  • 14. User-land startup snapshots Run-time generation, separate binary: from v18.8.0 ● Use the default Node.js binary to write snapshot to a separate blob for loading later $ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js $ node --snapshot-blob snapshot.blob # deserialize snapshot
  • 15. User-land startup snapshots Runtime generation, embedded binary: in v20.? ● Layer on top of single-executable application (work in progress) ● Use the default Node.js binary to generate a blob which includes the snapshot (and more), and inject it into one single executable ● No need to compile Node.js from source ● A single-line utility command to come $ echo '{"snapshot_main":"sea.js","output":"sea.blob"}' > sea.json $ node --experimental-sea-config sea.json $ cp node sea $ npx postject sea NODE_SEA_BLOB sea.blob --sentinel-fuse $NODE_SEA_FUSE $ ./sea # contains snapshot
  • 16. JS API: Synchronizing run-time states ● Node.js refreshes process.env and process.argv etc. when the snapshot is deserialized ● States computed from system states can be synchronized during deserialization. let debug_level = 0; function computeDebugLevel() { switch (process.env.DEBUG_LEVEL) { case 'none': debug_level = 0; break; case 'debug': debug_level = 1; break; } }
  • 17. JS API: Synchronizing run-time states const { addSerializeCallback, addDeserializeCallback, isBuildingSnapshot } = require(‘v8’).startupSnapshot; // Usual startup computeDebugLevel(); // Snapshot synchronization if (isBuildingSnapshot()) { addSerializeCallback(() => { debug_level = 0; /* reset */ }) addDeserializeCallback(computeDebugLevel); /* re-compute */ } // Or, defer the computation until deserialization if building snapshot if (!isBuildingSnapshot()) { computeDebugLevel(); } else { addDeserializeCallback(computeDebugLevel); }
  • 18. JS API: configure main function // In the snapshot: const greetings = { en_US: 'hello', zh_CN: '你好', es_ES: 'hola' }; 2. Configure the main function in the same snapshot script $ echo "console.log(greetings[process.env.LANGUAGE])" > hello.js $ LANGUAGE=en_US node --snapshot-blob snapshot.blob hello.js # logs "hello" 1. Pass a separate main script that does the logging $ LANGUAGE=en_US node --snapshot-blob snapshot.blob # logs "hello" require('v8').startupSnapshot.setDeserializeMainFunction(() => { console.log(greetings[process.env.LANGUAGE]); });
  • 19. Summary ● Startup snapshot has been integrated into Node.js core to speed up core startup ● Experimental user-land snapshot support is now available, with JS APIs in v8.startupSnapshot ● Support for single executable applications and more features is WIP
  • 20. Thanks ● @addaleax, @cjihrig, @jasnel, @legendecas, @RaisinTen, et al. ● Bloomberg & Igalia