SlideShare a Scribd company logo
1 of 20
Download to read offline
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

More Related Content

What's hot

NAND Flash から InnoDB にかけての話(仮)
NAND Flash から InnoDB にかけての話(仮)NAND Flash から InnoDB にかけての話(仮)
NAND Flash から InnoDB にかけての話(仮)Takanori Sejima
 
やってはいけない空振りDelete
やってはいけない空振りDeleteやってはいけない空振りDelete
やってはいけない空振りDeleteYu Yamada
 
Amazon Aurora - Auroraの止まらない進化とその中身
Amazon Aurora - Auroraの止まらない進化とその中身Amazon Aurora - Auroraの止まらない進化とその中身
Amazon Aurora - Auroraの止まらない進化とその中身Amazon Web Services Japan
 
NGINX Back to Basics: Ingress Controller (Japanese Webinar)
NGINX Back to Basics: Ingress Controller (Japanese Webinar)NGINX Back to Basics: Ingress Controller (Japanese Webinar)
NGINX Back to Basics: Ingress Controller (Japanese Webinar)NGINX, Inc.
 
PostgreSQLでスケールアウト
PostgreSQLでスケールアウトPostgreSQLでスケールアウト
PostgreSQLでスケールアウトMasahiko Sawada
 
こんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールこんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールdcubeio
 
PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)
PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)
PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)NTT DATA Technology & Innovation
 
Spannerに関する技術メモ
Spannerに関する技術メモSpannerに関する技術メモ
Spannerに関する技術メモEtsuji Nakai
 
スマホアプリ開発者のためのWeb api開発入門の入門
スマホアプリ開発者のためのWeb api開発入門の入門スマホアプリ開発者のためのWeb api開発入門の入門
スマホアプリ開発者のためのWeb api開発入門の入門Kenyu Miura
 
YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)
YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)
YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)NTT DATA Technology & Innovation
 
コンテナ時代にインフラエンジニアは何をするのか
コンテナ時代にインフラエンジニアは何をするのかコンテナ時代にインフラエンジニアは何をするのか
コンテナ時代にインフラエンジニアは何をするのかgree_tech
 
Best Practices for Becoming an Exceptional Postgres DBA
Best Practices for Becoming an Exceptional Postgres DBA Best Practices for Becoming an Exceptional Postgres DBA
Best Practices for Becoming an Exceptional Postgres DBA EDB
 
本当は恐ろしい分散システムの話
本当は恐ろしい分散システムの話本当は恐ろしい分散システムの話
本当は恐ろしい分散システムの話Kumazaki Hiroki
 
O/Rマッパーによるトラブルを未然に防ぐ
O/Rマッパーによるトラブルを未然に防ぐO/Rマッパーによるトラブルを未然に防ぐ
O/Rマッパーによるトラブルを未然に防ぐkwatch
 
Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)
Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)
Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)NTT DATA Technology & Innovation
 
今こそ知りたいSpring Batch(Spring Fest 2020講演資料)
今こそ知りたいSpring Batch(Spring Fest 2020講演資料)今こそ知りたいSpring Batch(Spring Fest 2020講演資料)
今こそ知りたいSpring Batch(Spring Fest 2020講演資料)NTT DATA Technology & Innovation
 
SQLチューニング入門 入門編
SQLチューニング入門 入門編SQLチューニング入門 入門編
SQLチューニング入門 入門編Miki Shimogai
 

What's hot (20)

NAND Flash から InnoDB にかけての話(仮)
NAND Flash から InnoDB にかけての話(仮)NAND Flash から InnoDB にかけての話(仮)
NAND Flash から InnoDB にかけての話(仮)
 
やってはいけない空振りDelete
やってはいけない空振りDeleteやってはいけない空振りDelete
やってはいけない空振りDelete
 
Amazon Aurora - Auroraの止まらない進化とその中身
Amazon Aurora - Auroraの止まらない進化とその中身Amazon Aurora - Auroraの止まらない進化とその中身
Amazon Aurora - Auroraの止まらない進化とその中身
 
NGINX Back to Basics: Ingress Controller (Japanese Webinar)
NGINX Back to Basics: Ingress Controller (Japanese Webinar)NGINX Back to Basics: Ingress Controller (Japanese Webinar)
NGINX Back to Basics: Ingress Controller (Japanese Webinar)
 
PostgreSQLでスケールアウト
PostgreSQLでスケールアウトPostgreSQLでスケールアウト
PostgreSQLでスケールアウト
 
PostreSQL監査
PostreSQL監査PostreSQL監査
PostreSQL監査
 
こんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールこんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツール
 
PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)
PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)
PostgreSQLのロール管理とその注意点(Open Source Conference 2022 Online/Osaka 発表資料)
 
Spannerに関する技術メモ
Spannerに関する技術メモSpannerに関する技術メモ
Spannerに関する技術メモ
 
スマホアプリ開発者のためのWeb api開発入門の入門
スマホアプリ開発者のためのWeb api開発入門の入門スマホアプリ開発者のためのWeb api開発入門の入門
スマホアプリ開発者のためのWeb api開発入門の入門
 
YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)
YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)
YugabyteDBを使ってみよう(NewSQL/分散SQLデータベースよろず勉強会 #1 発表資料)
 
コンテナ時代にインフラエンジニアは何をするのか
コンテナ時代にインフラエンジニアは何をするのかコンテナ時代にインフラエンジニアは何をするのか
コンテナ時代にインフラエンジニアは何をするのか
 
Best Practices for Becoming an Exceptional Postgres DBA
Best Practices for Becoming an Exceptional Postgres DBA Best Practices for Becoming an Exceptional Postgres DBA
Best Practices for Becoming an Exceptional Postgres DBA
 
本当は恐ろしい分散システムの話
本当は恐ろしい分散システムの話本当は恐ろしい分散システムの話
本当は恐ろしい分散システムの話
 
O/Rマッパーによるトラブルを未然に防ぐ
O/Rマッパーによるトラブルを未然に防ぐO/Rマッパーによるトラブルを未然に防ぐ
O/Rマッパーによるトラブルを未然に防ぐ
 
Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)
Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)
Kubernetes環境に対する性能試験(Kubernetes Novice Tokyo #2 発表資料)
 
今こそ知りたいSpring Batch(Spring Fest 2020講演資料)
今こそ知りたいSpring Batch(Spring Fest 2020講演資料)今こそ知りたいSpring Batch(Spring Fest 2020講演資料)
今こそ知りたいSpring Batch(Spring Fest 2020講演資料)
 
Java11へのマイグレーションガイド ~Apache Hadoopの事例~
Java11へのマイグレーションガイド ~Apache Hadoopの事例~Java11へのマイグレーションガイド ~Apache Hadoopの事例~
Java11へのマイグレーションガイド ~Apache Hadoopの事例~
 
SQLチューニング入門 入門編
SQLチューニング入門 入門編SQLチューニング入門 入門編
SQLチューニング入門 入門編
 
Aurora Deep Dive | AWS Floor28
Aurora Deep Dive | AWS Floor28Aurora Deep Dive | AWS Floor28
Aurora Deep Dive | AWS Floor28
 

Similar to Startup Snapshot in Node.js

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 workshopleffen
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.jsvaluebound
 
Nodejs web service for starters
Nodejs web service for startersNodejs web service for starters
Nodejs web service for startersBruce Li
 
Modern Development Tools
Modern Development ToolsModern Development Tools
Modern Development ToolsYe Maw
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
 
Intro to SpringBatch NoSQL 2021
Intro to SpringBatch NoSQL 2021Intro to SpringBatch NoSQL 2021
Intro to SpringBatch NoSQL 2021Slobodan Lohja
 
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 developerEdureka!
 
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 DeveloperEdureka!
 
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 waySylvain Rayé
 
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.jsasync_io
 
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 manifestLibbySchulze
 
GeoServer Developers Workshop
GeoServer Developers WorkshopGeoServer Developers Workshop
GeoServer Developers WorkshopJody Garnett
 
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 SolutionsRapidValue
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 
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 Sencha
 
Grunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous IntegrationGrunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous IntegrationDavid Amend
 

Similar to 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
 

More from 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 WPEIgalia
 
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...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 DevicesIgalia
 
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 MaintenanceIgalia
 
Optimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdfOptimizing Scheduler for Linux Gaming.pdf
Optimizing Scheduler for Linux Gaming.pdfIgalia
 
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 JITIgalia
 
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!Igalia
 
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 GStreamerIgalia
 
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 MesaIgalia
 
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 IgaliaIgalia
 
2023 in Chimera Linux
2023 in Chimera                    Linux2023 in Chimera                    Linux
2023 in Chimera LinuxIgalia
 
Building a Linux distro with LLVM
Building a Linux distro        with LLVMBuilding a Linux distro        with LLVM
Building a Linux distro with LLVMIgalia
 
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 GPUsIgalia
 
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 devicesIgalia
 
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 ChromeOSIgalia
 
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 webIgalia
 
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 shadersIgalia
 
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...Igalia
 
Status of Vulkan on Raspberry
Status of Vulkan on RaspberryStatus of Vulkan on Raspberry
Status of Vulkan on RaspberryIgalia
 
Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...Igalia
 

More from Igalia (20)

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
 
Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...Enable hardware acceleration for GL applications without glamor on Xorg modes...
Enable hardware acceleration for GL applications without glamor on Xorg modes...
 

Recently uploaded

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 

Recently uploaded (20)

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 

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