Node.js de Alto Rendimiento Potenciado por Rust y WebAssembly

Rate this content
Bookmark

En la era posterior a la Ley de Moore, debido a las limitaciones del hardware, necesitamos exprimir más rendimiento del hardware existente. Eso significa que el código nativo proporciona el mejor rendimiento. Sin embargo, la prevalencia del código nativo en el lado del servidor presenta desafíos para la seguridad y la administración de aplicaciones. El surgimiento y la llegada de Rust y WebAssembly ofrecen nuevas formas para que los desarrolladores escriban aplicaciones Node.js de alto rendimiento pero seguras.


En esta charla, cubriré los conceptos básicos de Rust y WebAssembly, así como también mostraré cómo integrarlos con Node.js. Aprenderás cómo y cuándo diseñar una aplicación web híbrida. Cómo puedes codificar las funciones de alto rendimiento en Rust en una máquina virtual de WebAssembly y finalmente cómo unir todo en una aplicación JavaScript de Node.js.

8 min
18 Feb, 2022

Video Summary and Transcription

Esta charla explora el uso de Rust y WebAssembly para mejorar el rendimiento de las aplicaciones Node.js. Al aprovechar la eficiencia y las características de seguridad de Rust, y compilarlo en bytecode de WebAssembly, los desarrolladores pueden lograr cálculos de alto rendimiento mientras garantizan la seguridad. WebAssembly permite la comunicación directa con el hardware nativo y está optimizado para aplicaciones en el lado del servidor, lo que lo hace adecuado para tareas como inferencia de IA y bases de datos de almacenamiento. En general, esta charla resalta el potencial de combinar JavaScript, Rust y WebAssembly para construir aplicaciones eficientes y portátiles.

Available in English

1. Introducción a Node.js de alto rendimiento

Short description:

Hola a todos. Soy Shivai Lamba. Hoy mi charla relámpago en el Congreso de Node.js 2022 trata sobre el alto rendimiento de Node.js impulsado por Rust y WebAssembly. La ley de Moore establece que el número de transistores en un microchip se duplica cada dos años. Para superar las limitaciones del hardware, debemos mejorar el rendimiento del software asegurando la seguridad. Rust es un lenguaje de programación seguro y moderno que ofrece eficiencia y rendimiento superior en comparación con Node.js. Podemos usar WebAssembly para compilar el código de Rust en bytecode y gestionarlo con una máquina virtual. WebAssembly proporciona seguridad, un tiempo de ejecución ligero y portátil, eficiencia extrema y seguridad en tiempo de ejecución. Esta charla se centra en el uso de JavaScript, Rust y WebAssembly para construir aplicaciones con el rendimiento de Rust y la seguridad y portabilidad de WebAssembly.

Hola a todos. Soy Shivai Lamba. Actualmente soy miembro del grupo de interés especial de TensorFlow.js y también soy miembro del grupo de trabajo de India. También soy mentor de TensorFlow, específicamente para TensorFlow.js. Y hoy mi charla relámpago en el Congreso de Node.js 2022 tratará sobre el alto rendimiento de Node.js impulsado por Rust y WebAssembly. Ahora, primero, hablemos brevemente sobre la ley de Moore. Todos saben que la ley de Moore establece que el número de transistores en un microchip se duplica cada dos años. Pero si observamos los últimos cinco años, la limitación de tamaño ha limitado la cantidad de transistores que se pueden colocar en un chip. Y eso ha resultado en un efecto de estancamiento del rendimiento del hardware de la computadora. Esto significa que, para superar esta limitación impuesta por el hardware, debemos mejorar el software mediante prácticas que mejoren el rendimiento del software. Y al mismo tiempo, estas mejoras de rendimiento del software también deben ser seguras. Para eso, vamos a ver algunas herramientas que se pueden utilizar con diferentes aplicaciones y lenguajes del lado del servidor, como Node.js y Rust. Ahora, ¿por qué elegir Rust? Tenemos muchos lenguajes de programación heredados como C++, pero estos son propensos a errores. Pero Rust ofrece un lenguaje seguro y moderno que es igual de eficiente, si no más, que C++. Y también es mucho más capaz que Node.js en términos de rendimiento. Realmente puedes potenciarlo con muchas aplicaciones de alto rendimiento que se ejecutan de manera muy sencilla con la ayuda de Rust.

Y luego, surge la pregunta de cómo podemos usar Rust para programar en la web. Bueno, la forma anterior era compilarlo en bibliotecas y extensiones nativas con runtimes existentes como Node.js. Pero este enfoque resultó ser bastante inseguro y también requería un alto mantenimiento. Entonces, ¿cuál es la mejor manera? Bueno, puedes usar WebAssembly, que es esencialmente una forma de poder... proporciona las instrucciones para poder utilizar bytecodes que ayudan a interactuar con la aplicación en la que lo estás ejecutando, específicamente en la web, con las aplicaciones de nivel inferior que se ejecutan en la plataforma. Y podemos compilar el código de Rust en bytecode y luego gestionarlo con la ayuda de una máquina virtual como WebAssembly. ¿Y cuáles son algunos de los beneficios de la máquina virtual de WebAssembly, que hoy también se conoce como el tiempo de ejecución de Wasmage? Bueno, proporciona mucha seguridad de forma predeterminada. Es extremadamente ligero y portátil. Proporciona una eficiencia extrema porque utiliza técnicas como la compilación anticipada. También proporciona seguridad en tiempo de ejecución. Y está específicamente optimizado para muchas aplicaciones del lado del servidor. Y eso nos lleva al ecosistema que tenemos para esta charla. Queremos usar JavaScript por su facilidad de uso para construir aplicaciones, al mismo tiempo que tenemos el rendimiento de Rust y la seguridad y portabilidad de algo como WebAssembly. Y eso nos lleva a esta arquitectura que tenemos.

2. Using WebAssembly for High Performance

Short description:

Podemos utilizar una máquina virtual basada en WebAssembly para ejecutar programas basados en Rust con tareas altamente computacionales, lo que hace que las aplicaciones de Node.js sean más eficientes. Al escribir tareas intensivas en Rust y utilizar funciones de JavaScript para llamar a funciones basadas en WebAssembly, podemos agrupar y compilar funciones de Rust en bytecode alojado en la máquina virtual de WebAssembly. Esto no solo asegura la aplicación, sino que también permite cálculos de alto rendimiento con Rust. WebAssembly se puede utilizar para diversas tareas, incluyendo inferencia de IA y bases de datos de almacenamiento, ya que permite la comunicación directa con el hardware nativo y está optimizado para aplicaciones del lado del servidor.

En general, las ejecuciones de Node.js runtimes se basarán en un runtime basado en C++. Pero, por supuesto, tenemos la solución alternativa de poder tener esencialmente una máquina virtual basada en WebAssembly que puede ejecutar los programas basados en Rust que tienen tareas altamente computacionales y que pueden ayudar a que las aplicaciones basadas en Node.js sean altamente eficientes. Y veamos cómo funciona eso en realidad. Entonces, lo que estamos haciendo es que tenemos nuestra aplicación de Node.js donde todas las tareas altamente intensivas no están escritas en Node.js, sino que están escritas en Rust. Así que con la ayuda de una función de JavaScript, llamaremos a las funciones basadas en WebAssembly que ayudan a agrupar la función de Rust y compilarla en un bytecode que luego se sirve y se aloja en la máquina virtual de WebAssembly, en este caso, Wasmx o SSVM. Y eso no solo ayuda a asegurar la aplicación, sino que también todas estas competiciones altamente intensivas que deben tener lugar ahora se realizan con la ayuda de Rust. Y solo tienes que llamar a esta función con la ayuda de tu entorno de Node.js. Y, por supuesto, puedes usarlas para muchas cosas diferentes, incluyendo inferencia de IA, porque puedes comunicarte directamente con el hardware nativo que es tu hardware de IA, o puedes usarlas para cosas como bases de datos de almacenamiento, ya que WebAssembly está altamente optimizado para aplicaciones del lado del servidor. Entonces, ¿cómo empezar? Bueno, como discutimos, la aplicación de host es esencialmente una aplicación web basada en Node.js escrita en JavaScript y se utiliza para realizar llamadas a funciones basadas en WebAssembly y el bytecode de WebAssembly se escribe primero en Rust, que luego se convierte en un bytecode de WebAssembly y se ejecuta dentro del tiempo de ejecución de WebAssembly y se llama con la ayuda de la aplicación de Node.js. Y para configurar este entorno completo, necesitarías al menos una versión moderna de Ubuntu. También necesitarías cosas como el lenguaje Rust, Node.js, el tiempo de ejecución de Wasm Edge y Wasm Edge y otra cosa como la herramienta de compilación de Rust a WebAssembly que ayudará a compilar desde Rust hasta el bytecode. Y ahora veamos un ejemplo de código. Entonces, para un código de inicio para comenzar con todo este ecosistema, puedes ir al siguiente enlace en el repositorio de GitHub de Second State que proporciona un inicio de NodeJs. Aquí, he proporcionado un pequeño fragmento de código. Como puedes ver, en la parte superior, hemos incluido una función segura. Esto se genera a partir de WebAssembly. Una vez que realmente construimos la función de Rust. Se convierte en bytecode y también este código basado en WebAssembly que puedes importar directamente. Y hemos hecho una simple llamada al servidor que básicamente agrega un parámetro de consulta al final de la llamada a la API y simplemente agrega un nombre. Y esto es lo que enviamos como una solicitud GET. Y esto aparece en la respuesta como hola con cualquier parámetro de consulta que hayamos dado con nuestro programa. Por supuesto, puedes usar esto para tareas mucho más intensivas computacionalmente. Por ejemplo, inferencia de machine learning, donde puedes tener, como, una imagen y pasarla como un parámetro de consulta y tienes tu inferencia real de machine learning que tiene lugar en Rust y obtienes la respuesta. Así que espero que esto te dé una buena idea de lo que está sucediendo detrás de escena. Bueno, con eso, concluyo mi charla relámpago. Si tienes alguna otra pregunta, no dudes en conectarte conmigo en mi Twitter, y espero que tengas un maravilloso resto del Congreso de Node.js. Muchas gracias.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
Vue.js London Live 2021Vue.js London Live 2021
8 min
Utilising Rust from Vue with WebAssembly
Top Content
Rust is a new language for writing high-performance code, that can be compiled to WebAssembly, and run within the browser. In this talk you will be taken through how you can integrate Rust, within a Vue application, in a way that's painless and easy. With examples on how to interact with Rust from JavaScript, and some of the gotchas to be aware of.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.