<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Seth Lutske on Medium]]></title>
        <description><![CDATA[Stories by Seth Lutske on Medium]]></description>
        <link>https://medium.com/@seth.lutske?source=rss-60fca2adb21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MU1J6G01bJG1f29efUoUIw.png</url>
            <title>Stories by Seth Lutske on Medium</title>
            <link>https://medium.com/@seth.lutske?source=rss-60fca2adb21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:33:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seth.lutske/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating, Serving, and Rendering Custom VectorTiles]]></title>
            <link>https://medium.com/@seth.lutske/creating-serving-and-rendering-custom-vectortiles-c843c0280c19?source=rss-60fca2adb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/c843c0280c19</guid>
            <category><![CDATA[web-mapping]]></category>
            <category><![CDATA[leafletjs]]></category>
            <category><![CDATA[maplibre]]></category>
            <category><![CDATA[vector-tiles]]></category>
            <category><![CDATA[openstreetmap]]></category>
            <dc:creator><![CDATA[Seth Lutske]]></dc:creator>
            <pubDate>Tue, 02 May 2023 16:24:39 GMT</pubDate>
            <atom:updated>2023-05-02T16:24:39.223Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The journey into a ubiquitous but poorly documented process</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzS-dTzALeVLFnhSdWjNZw.png" /></figure><p>Customizing webmaps has become hugely popular in recent years. Some companies are thriving on the needs of businesses and developers to provide maps with data content display styles customized to fit their needs. Companies like Mapbox, ESRI, MapTiler, Thunderforest, and Jawg (to name a few) offer services to customize map tiles, and host your custom tiles, usually at a price.</p><p>I recently found myself in a scenario where I needed to create global, custom basemaps, to be hosted in an air-gap environment. Using someone’s external tile service was not an option. My team was already using a worldwide set of raster tiles, created using <a href="https://github.com/tilemill-project/tilemill">tilemill</a>. But since we needed several variations of global tiles, our basemap tiles weighed several gigabytes.</p><p>My goal was to use vector tiles. With vector tiles, a single tile set could be used for multiple styles. That would save disk space, as well as allow us to customize exactly what kinds of data were shown on the map, and with what colors, symbols, etc. Here is the process I followed to make this happen.</p><h3>Generating tiles with hand-picked, open source data</h3><p><a href="https://wiki.openstreetmap.org/wiki/Main_Page">OpenStreetMap</a> (OSM) is a free, open source data store for global geodata. It is the wikipedia of GIS data — open source and community driven. When you look at tiling services like Mapbox or MapTiler, a huge amount of their data originates from OSM. If you want to extract this data yourself and transform it into x/y/z vectortiles, the <a href="https://openmaptiles.org/">openmaptiles</a> project can do this. Their documentation on <a href="https://openmaptiles.org/docs/generate/generate-openmaptiles/">generating your own map</a> is a surface-level introduction to the process. In short:</p><ul><li>Get docker up and running on your machine</li><li>git clone <a href="https://github.com/openmaptiles/openmaptiles.git">https://github.com/openmaptiles/openmaptiles.git</a></li><li>docker compose pull</li><li>run ./quickstart.sh</li></ul><p>You’ll want to do this on a machine as powerful as you can find / afford, that you can leave running for up to several days. If you have cloud compute resources, use them!</p><p>A good discussion of what happens next can be found in the youtube talk, <a href="https://www.youtube.com/watch?v=uDT7C7Mg83s&amp;t=967s">Generating a World-Wide Vector Tile Map from OpenStreetMap with PostGIS, the story of OpenMapTiles</a>. In essence:</p><ul><li>A source data .pbf file is downloaded for you area of interest. Running ./quickstart.sh without any arguments will default to downloading data for Albania, but you can look into the quickstart.sh script for a full list of countries. You can also run ./quickstart planet to download worldwide data. <strong>Warning!</strong> The whole planet weighs 70–80 GB, so be patient.</li><li>Using dockerized <a href="https://postgis.net/">PostGIS</a>, a series of SQL queries is run against the downloaded source data.</li><li>The queries write to .pbf tile files in the classic x/y/z format, and organized in a .mbtiles database file.</li></ul><p>The meat and potatoes of the openmaptiles project are its SQL queries for the various layer types we are interested in. Looking into the openmaptiles.yaml file, we can see a list of those layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*526BGG6Y_frqjRRrJyWyBA.png" /><figcaption>A list of layers that will be included in your end result vectortiles.</figcaption></figure><p>In the /layers directory, there is a directory associated with each one of these layers listed above. And each directory has its own .sql file to make the query against the root .pbf dataset to process data for that layer. For example, looking at layers/landcover/landcover.sql</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRRkz4cfqB7MyzdfEGbCqw.png" /><figcaption>As a non-SQL expert, I won’t even bother trying to interperet the complexity of the database queries happening here.</figcaption></figure><p>For my use case, I didn’t need to display (or store!) all layers available in OSM. So in the openmaptiles.yaml , I commented them out before running the ./quickstart.sh script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qPbvNbMozoF7UBFJrGqpw.png" /></figure><p>You can also specify a minzoom and maxzoom range in this file so that your end result contains the zoom levels you need.</p><p>After running ./quickstart.sh &lt;area_of_interest&gt; , walk away for 10 minutes, or 10 hours, or 4 days, depending on how large an area you are generating tiles for, and how powerful your machine is. Once the process is complete, you’ll end up with your .mbtiles file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*DZjMDGpgJrCCz8-Q3XOnoQ.png" /><figcaption>Hooray!</figcaption></figure><p>If you need to <em>add</em> your own custom data to the tiles, that process is discussed in the openmaptiles docs on <a href="https://openmaptiles.org/docs/generate/custom-vector-from-postgis/">Custom vector tiles from PostGIS</a>, as well as in Tobin Bradley’s YouTube video <a href="https://www.youtube.com/watch?v=ONi7g-SBPvM">Removing, Modifying, and Adding layers to OpenMapTiles</a>.</p><h3>Serving your tiles</h3><p>Serving x/y/z tiles is the relatively easy part. There are a number of out-of-the-box mbtiles servers you can use. I’ve had good luck with <a href="https://maptiler-tileserver.readthedocs.io/en/latest/">tileserver-gl</a>, (made by the same team as openmaptiles), as well as <a href="https://github.com/asd20752/node-mbtiles">node-mbtiles</a>, but there are many ready-to-go mbtiles servers out there that can suit your needs. For this article, we’ll go with a modified version of node-mbtiles, as we’ll need to add some special routes for handling style information later. I like node-mbtiles as well because it makes it easy to serve different tilesets at different endpoints. Here is a modified version that can handle both raster and vector mbtiles databases:</p><pre>// index.js<br><br>const express = require(&quot;express&quot;);<br>const cors = require(&quot;cors&quot;);<br>const sqlite3 = require(&quot;sqlite3&quot;);<br><br>let port = 5000;<br><br>// Object to reference various mbtiles DBs by endpoint name <br>const databases = {<br>  vectortiles: {<br>    filePath: &quot;vectortiles.mbtiles&quot;, // the vectortiles file we created<br>    type: &quot;vector&quot;,<br>  },<br>  rastertiles: {<br>    filePath: &quot;rastertiles.mbtiles&quot;, // other raster tiles you may have<br>    type: &quot;raster&quot;,<br>  },<br>};<br><br>const databaseAlias = Object.keys(databases);<br><br>databaseAlias.forEach((element) =&gt; {<br>  databases[element].db = new sqlite3.Database(<br>    databases[element].filePath,<br>    sqlite3.OPEN_READONLY,<br>    (err) =&gt; {<br>      if (err) {<br>        console.log(&quot;Failed to load: &quot; + databases[element].filePath);<br>        throw err;<br>      }<br>    }<br>  );<br>});<br><br>const requestListener = function (req, res) {<br>  const args = req.url.split(&quot;/&quot;);<br>  const dbAlias = args[1];<br>  const z = args[2] ? parseInt(args[2]) : undefined;<br>  const x = args[3] ? parseInt(args[3]) : undefined;<br>  const y = args[4] ? parseInt(args[4]) : undefined;<br><br>  if (databaseAlias.includes(dbAlias)) {<br>    let mod_y = Math.pow(2, z) - 1 - y;<br><br>    databases[dbAlias].db.get(<br>      `SELECT * FROM tiles <br>           WHERE zoom_level = ${z} <br>           AND tile_column = ${x} <br>           AND tile_row = ${mod_y}`,<br>      (err, row) =&gt; {<br>        if (!err &amp;&amp; row !== undefined) {<br>          // For vector tiles, need to define content type as octet-stream<br>          if (databases[dbAlias].type === &quot;vector&quot;) {<br>            headers[&quot;Content-Type&quot;] = &quot;application/octet-stream&quot;;<br>            // Need to specify as gzip if pbfs are gzipped, which they<br>            // are when being generated by openmaptiles tooling<br>            headers[&quot;Content-Encoding&quot;] = &quot;gzip&quot;;<br>          }<br>          // For raster tiles, need to define content type as image/png<br>          else {<br>            headers[&quot;Content-Type&quot;] = &quot;image/png&quot;;<br>          }<br><br>          res.writeHead(200, headers);<br>          res.end(row.tile_data);<br>        } else {<br>          res.writeHead(404, headers);<br>          res.end();<br>        }<br>      }<br>    );<br>  } else {<br>    res.writeHead(400);<br>    res.end();<br>  }<br>};<br><br>const app = express();<br>app.use(cors());<br><br>app.get(&quot;*&quot;, requestListener);<br><br>app.listen(port, () =&gt;<br>  console.log(&quot;Tileserver listening for connections on port: &quot; + port)<br>);</pre><h3>Consuming your tiles — Tiling and Styling</h3><p>Front-end mapping libraries like mapbox-gl or maplibre (mapbox-gl’s open source fork) are vector-tile-native libraries, meaning their primary focus is on rendering vectortiles as basemaps. <a href="https://maplibre.org/maplibre-gl-js-docs/example/simple-map/">Creating a map with maplibre is easy</a>:</p><pre>var map = new maplibregl.Map({<br>  container: &#39;map&#39;, // container id<br>  style: &#39;https://demotiles.maplibre.org/style.json&#39;, // style URL<br>  center: [0, 0], // starting position [lng, lat]<br>  zoom: 1 // starting zoom<br>});</pre><p>That’s it. Wait, <em>what</em>? Where is the reference to the actual data to be shown on the map? The style.json referenced here follows a specific schema, which you can read about in the <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/">Mapbox Style Specification</a> docs. The style.json has properties like sources , spites and glyphs , which point at the other resources needed to render your map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*xMAun_yO5cArLSaFRQpK9A.png" /><figcaption>Your mapping library points to the style.json, which points to tiles.json, which points to you x/y/z tile endpoints. Style.json also references sprite and glyph files needed for rendering in the front end.</figcaption></figure><p>When working with mapbox, mapbox provides all these files from their API, from the style.json to the sprites to the tiles themselves. You can create custom styles in <a href="https://studio.mapbox.com/">Mapbox Studio</a>, or with <a href="https://maputnik.github.io/editor/#0.7/0/0">Maputnik</a>. (Google and ESRI also have their own vector-tiling tools, but they also have unique implementations for vector tiles, specific to their mapping APIs.) If you want to replicate and self-host these files from either Mapbox Studio or Maputnik, you need an account and api key. But this will be a one-time download to use as the basis of what you will serve yourself.</p><p>In mapbox studio, click “Share” in the upper right corner of your style editor, and you’ll find a download link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Yv3SlXar11Ew6i5jYuEf8g.png" /></figure><p>Or with Maputnik, you can export the style:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*jxn3r_Dd9uspMmZxfAblbQ.png" /></figure><p>In either case, the downloaded files offer a starting point to tell your map what data to use and how to style it. You’ll need a few more resources as well, so keep reading.</p><h3>Putting it all together on the tileserver</h3><p>If you need to serve the styling resources yourself, create or copy a style.json and serve that from your tile. Your style.json will have a sources property, which point at various data sources for the map. These can be named anything you like, but the keys of sources must match with the source properties of the layers styles in style.json . For example, if I name my source medium_example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Xj0RdFjnHbmsiCXdQmSAw.png" /><figcaption>In style.json, the name of a source must match the source property of the styles that should apply to it.</figcaption></figure><p>Notice that the url property of this source points to a tiles.json file, also being served by my server. In tiles.json , you must set the tiles property to the address of your vectortile x/y/z endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*k2IKRgVuAK7jVhFFDtunRA.png" /><figcaption>In tiles.json</figcaption></figure><p>Now there is a clear line between your frontend and your tile server, as well as styling information. You will also need to add sprites and fonts. The process for doing this is well explained in <a href="https://openmaptiles.org/docs/host/tileserver-php/">Serve map tiles with PHP</a>. In essence, copy all asset files to your server and make them available as static assets. Then point the sprite and glyph properties of your style.json at them. In my case, I didn’t need any sprites, but I did need 2 fonts. I put everything in a styles folder on the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*yDo2Ht49BLWt8Sh8xbu6Qw.png" /></figure><p>And then using express, I set up my server to serve any files within this folder as static files:</p><pre>// index.js<br><br>...<br><br>app.get(&quot;*&quot;, requestListener);<br>// Serve all files within the &#39;styles&#39; folder as static files,<br>// available at the endpoint &#39;/styles/path/to/file.extension<br>app.use(&quot;/styles&quot;, express.static(&quot;styles&quot;));<br><br>app.listen(port, () =&gt;<br>  console.log(&quot;Tileserver listening for connections on port: &quot; + port)<br>);</pre><p>Now we can point the front end at out own style.json :</p><pre>var map = new maplibregl.Map({<br>  container: &#39;map&#39;, <br>  style: &#39;http://localhost:5000/styles/style.json&#39;, <br>  center: [0, 0], <br>  zoom: 1 <br>});</pre><p>And of course you will need to prefix the other urls within style.json and tiles.jsonto use http://localhost:5000/ , or whatever your base route is.</p><h3>Bonus: vectortile basemaps in LeafletJS</h3><p>My goal was to use leaflet.js for my frontend maps. But leaflet does not have native support for vector tiles, and the handful of plugins that claim to enable vectortiles in leaflet are not at all designed for generating vectortile <em>basemaps. </em>Plugins like <a href="https://leaflet.github.io/Leaflet.VectorGrid/vectorgrid-api-docs.html">Leaflet.VectorGrid</a> or <a href="https://gitlab.com/jkuebart/Leaflet.VectorTileLayer">Leaflet.VectorTileLayer</a> both explain they are designed render complex or dense geometries from vectortiles in a leaflet map, <em>not </em>to render vectortiles as fully styled basemaps.</p><p>One option is to use the <a href="https://github.com/maplibre/maplibre-gl-leaflet">maplibre-gl-leaflet</a>, as described in MapTiler’s own tutorial, <a href="https://docs.maptiler.com/leaflet/vector-tiles-in-leaflet-js/">Vector tiles in Leaflet JS</a>:</p><pre>import L from &quot;leaflet&quot;;<br>import &quot;leaflet/dist/leaflet.css&quot;;<br>import &quot;@maplibre/maplibre-gl-leaflet&quot;;<br>import &quot;maplibre-gl/dist/maplibre-gl.css&quot;;<br><br>var map = L.map(&quot;map&quot;);<br><br>const gl = L.maplibreGL({<br>  style: &quot;http://localhost:5000/styles/styles.json&quot;<br>});<br><br>gl.addTo(map);</pre><p>And voila! A custom vectortile basemap, with customized data sources, within leafletjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_mfoulkAdSUYH0tDViswg.png" /></figure><p>If you want a different map style, you can have any number of style.json files, which all references the same tiles. In this way, your data source is singular and takes up less space.</p><p>Ok, so in the end, various pieces of the process <em>are</em> pretty well documented. The openmaptiles project explains how to extract OSM data to suit your needs, as well as how to host your own style.json and friends. You’ll also find documentation on the schema for a style.json , but the details of how they bridge the gap between your raw tile data and your front-end display is not always clear. Hopefully this article has helped you connect the dots.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c843c0280c19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Automate Performance Profiling in Node.js]]></title>
            <link>https://medium.com/bitsrc/how-to-automate-performance-profiling-in-nodejs-57524b8f763f?source=rss-60fca2adb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/57524b8f763f</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Seth Lutske]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 02:44:28 GMT</pubDate>
            <atom:updated>2025-03-06T08:42:02.455Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating performance metrics for your Node.js applications just got much easier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_OiV_0IT02oos7oyFepOJA.jpeg" /><figcaption>Creating performance metrics doesn’t have to be a pain</figcaption></figure><p>Performance profiling is very useful for finding out where your application is slow, and how you can make it more efficient.</p><p>With the right tools, profiling a Node.js application can be fairly straightforward. But the experience described by many tutorials is so <em>involved</em>, and requires the developer to walk through the profiling process step by step, every time.</p><p>This article describes how you can automate the process.</p><figure><a href="https://bit.cloud/"><img alt="Build in AI speed — Compose enterprise-grade applications, features, and components" src="https://cdn-images-1.medium.com/max/1024/1*yX0vq3scSudyT61IuWFuEg.png" /></a><figcaption>Build in AI speed — Compose enterprise-grade applications, features, and components</figcaption></figure><h3>Useful tools</h3><p>In addition to your Node.js project, there are a few tools we’ll need. We’ll go through these more in depth as we outline the process:</p><ul><li><a href="https://pm2.keymetrics.io/">PM2</a></li><li><a href="https://httpd.apache.org/docs/2.4/programs/ab.html">Apache Bench</a></li><li><a href="https://github.com/hyj1991/v8-profiler-next">v8-profiler-next</a></li><li><a href="https://github.com/jeffbski/wait-on">wait-on</a></li></ul><h3>A simple application</h3><p>Let’s start with a simple application we want to profile: an Express server. Your application can be any Node.js program, whether it’s a web server, image file processor, complex mathematical algorithm, or anything else.</p><p>The principles we use to profile an Express server can be applied anywhere.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4b2e0f073683fe686d1d4afe5f4f8e/href">https://medium.com/media/aa4b2e0f073683fe686d1d4afe5f4f8e/href</a></iframe><p>We’ve set up a simple web server, which has two routes.</p><p>One performs a simple calculation and returns the result, and the other performs a complex, CPU-heavy calculation, and returns the result.</p><p>The server runs on the port specified by process.env.PORT or defaults to port 8080. In our package.json, we create a script to run the server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71feee361d6fa1c7afd4616d9f17f694/href">https://medium.com/media/71feee361d6fa1c7afd4616d9f17f694/href</a></iframe><h3>Create a profiler</h3><p><a href="https://github.com/hyj1991/v8-profiler-next">v8-profiler-next</a> is the unofficial (but much needed) successor to the official but obsolete <a href="https://github.com/node-inspector/v8-profiler">v8-profiler</a>. It offers programmatic tools for starting and stopping the Node.js profiler from within your code, and is compatible with the latest version of Node.js.</p><p>For convenience, we can create a profiler class that can help us specify when and where to leverage the v8-profiler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e21bc618722f0eb8685567da048207b/href">https://medium.com/media/0e21bc618722f0eb8685567da048207b/href</a></iframe><p>The Profiler class has methods to start and finish profiling programmatically, if the active condition is met.</p><p>On finish, a <strong>.cpuprofile</strong> file will be written to a /&lt;outputDir&gt; directory <em>(more on </em><strong><em>.cpuprofile</em></strong><em> files later)</em>.</p><p>I recommend adding the profiles directory to your .gitignore file.</p><h3>Use the profiler…sometimes</h3><p>The profiler is a powerful tool, but you don’t want to use it every time your server runs. Rather, you’ll want to use only when you want to profile the app.</p><p>We can control the flow of whether or not we’re using the profiler by connecting environment variables to the active option when creating a new profiler.</p><p>Let’s add some more code to our index.js file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05f57152891f6ff4b9575b58044487b6/href">https://medium.com/media/05f57152891f6ff4b9575b58044487b6/href</a></iframe><p>We created a new Profiler instance that only runs the v8 profiler when process.env.PROFILER exists. As soon as a route is accessed, the profiler starts.</p><p>The calculations are performed, and after they are sent back to the requester, the profiler finishes, and writes a <strong>.cpuprofile</strong>.</p><p>All the pieces are in place to profile the application route by route.</p><h3>Automating the process</h3><p>While our Profiler is very useful, it still requires a lot of manual work to generate a metric of the app’s performance.</p><p>We need to start the server with certain environment variables, then use a tool to make requests to certain routes (a browser, Postman, Apache Bench, etc), and then shut down the server.</p><p>But with a bash script and some creative use of PM2, this can all be condensed into a single NPM command.</p><p>Let’s add a new NPM script to run a bash script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c06da1cf89095cb538d11627745e0f98/href">https://medium.com/media/c06da1cf89095cb538d11627745e0f98/href</a></iframe><p>This NPM script will run a local bash script in the project’s /scripts directory.</p><p>Here’s what that bash script might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/504ada42bbe1576d6f4ca25cee192511/href">https://medium.com/media/504ada42bbe1576d6f4ca25cee192511/href</a></iframe><h4>Let’s break this down step by step</h4><p><strong>export PORT=4000</strong></p><p><strong>export PROFILER=true</strong></p><p><strong>export OUTPUT_DIR=”profiles/$(date +%s)”</strong></p><ul><li>Here we establish some crucial environment variables we saw earlier in the code, which will persist through the life of the shell running this script.</li><li>The server will run on port 4000, but you can choose any port that won’t interfere with other processes you have running. It sets the PROFILER environment variable to true, which means your profiler will actually run.</li><li>It also sets the output directory of any profiling metric files to a unified location. I set it to be a folder named after the unix timestamp of the current moment, but you can choose any unique id.</li></ul><p><strong>pm2 start npm — name server-profiler — start</strong></p><ul><li>Here we leverage PM2 to run the npm start command of your package.json.</li><li>It gives a name to the process for PM2’s internal use, which we’ll need in the last step for cleanup.</li><li>A quick view of PM2 running processes after running this command will look like this (pm2 ls):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*jDdobYMHQsAZcwvFPEMfRA.png" /></figure><p><strong>npx wait-on </strong><a href="http://localhost:4000/"><strong>http://localhost:4000</strong></a></p><ul><li>Depending on your codebase, you may need to wait for your server to start and become available to take requests before moving on.</li><li>We use <a href="https://www.npmjs.com/package/wait-on">wait on</a> to wait for the server to become ready, before pinging it with any requests.</li></ul><p><strong>ab -n 1 </strong><a href="http://localhost:4000/api/complex"><strong>http://localhost:4000/api/complex</strong></a><strong> &gt; &quot;./${OUTPUT_DIR}/ABResults.txt&quot; 2&gt;&amp;1</strong></p><ul><li>Apache Bench (ab) is a powerful tool for benchmarking servers’ responses to requests. It comes preinstalled in many OSs, and deserves its own series of articles/tutorials to cover its total breadth of power.</li><li>In this case, we’re using it make a single GET request to our server’s api/complex route.</li><li>Apache Bench creates its own output with results about how quickly your server responded. This command writes the results to a file in our directory called ABResults.txt, rather than just printing them to the shell console.</li><li>Apache Bench has other options for outputting results to files as well, but I find its standard output to be the most useful.</li></ul><p><strong>pm2 stop server-profiler</strong></p><p><strong>pm2 delete server-profiler</strong></p><ul><li>Here we use the name we assigned to our process earlier to do some cleanup.</li><li>PM2 stops the server, and deletes the process.</li></ul><h3>The Results</h3><p>When the bash script is complete, we’ll have a new folder in our projects root directory called profiles, with a subdirectory named after the unix timestamp at which the script ran.</p><p>In that folder, we’ll have 2 files — the results of Apache Bench, and the <strong>.cpuprofile</strong> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*NGorRtgQxlYACbmuTfN0PQ.png" /></figure><p>The Apache Bench results for an example project look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*mH8SG9c8zBxil3KWn58fFA.png" /></figure><p>We see that the time per request is over 17 seconds. Terrible!</p><p>We can look into our <strong>.cpuprofile</strong> file for some hints on what is happening. The <strong>.cpuprofile</strong> file is a measure of how long the CPU spends executing various functions and operations in your code.</p><p>It can be viewed in Chrome or VSCode in various ways (as a flamegraph, JSON, or sortable list).</p><p>I personally find it most useful to view as a sortable list, sorted by total time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*z_ITspz-T-ItNnlZhlpC6w.png" /><figcaption>This is the .cpuprofile from a real project, so file paths and names are different than the sample code.</figcaption></figure><p>We can see that the CPU is spending quite a lot of time executing <strong>lodash</strong> cloning functions. A closer look into the top CPU spender:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*G5ouPbD2XQAJM7osWVIGzQ.png" /></figure><p>Clearly there is some bad logic in the complexCalculation function causing a recursive use of the clone function, which is slowing down performance. Now we know where to focus our efforts in making the code more efficient.</p><h3>Conclusion</h3><p>Setting up a profiling procedure for a Node.js application can be complex and clunky.</p><p>Now we can do it with a single NPM script: npm run profile. This will launch your application, make network requests (if necessary), record the performance of both the requests as well as the code itself, and perform all necessary cleanup.</p><p>Analyzing the performance of your Node application just became a breeze!</p><h3>Build composable web applications</h3><p>Don’t build web monoliths. Use <a href="https://bit.dev/">Bit</a> to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable frontends and backends with a powerful and enjoyable dev experience.</p><p>Bring your team to <a href="https://bit.cloud/">Bit Cloud</a> to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. <a href="https://bit.dev/"><strong>Give it a try →</strong></a></p><figure><img alt="https://cdn-images-1.medium.com/max/800/1*ctBUj-lpq4PZpMcEF-qB7w.gif" src="https://cdn-images-1.medium.com/proxy/1*ctBUj-lpq4PZpMcEF-qB7w.gif" /></figure><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/the-composable-enterprise-a-guide-609443ae1282">The Composable Enterprise: A Guide</a></li><li><a href="https://blog.bitsrc.io/7-tools-for-faster-frontend-development-in-2022-43b6f663c607">7 Tools for Faster Frontend Development in 2022</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57524b8f763f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/how-to-automate-performance-profiling-in-nodejs-57524b8f763f">How to Automate Performance Profiling in Node.js</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallelizing Cypress with Jenkins, AWS, and Sorry-Cypress]]></title>
            <link>https://medium.com/geekculture/parallelizing-cypress-with-jenkins-aws-and-sorry-cypress-8241331fe50f?source=rss-60fca2adb21------2</link>
            <guid isPermaLink="false">https://medium.com/p/8241331fe50f</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Seth Lutske]]></dc:creator>
            <pubDate>Thu, 01 Jul 2021 21:21:06 GMT</pubDate>
            <atom:updated>2021-07-06T16:46:34.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJrnP7IUAOY-jFpKSf3j9A.jpeg" /></figure><p>Cypress.io is an elegant end-to-end test runner for any front end project, and has become an industry standard. But for many enterprise-level projects, cypress tests stack up, and can take lots of time to run. This can slow down your CI/CD builds, and ultimately your project’s development.</p><p>If you’re using Jenkins, and you have access to cloud compute resources, you can run cypress in parallel across multiple virtual machines. This will significantly cut down your cypress run time. This article is a recipe for how to do that.</p><h3>What you will need</h3><ul><li>Your project, which includes cypress tests</li><li>A Jenkins server</li><li>Cloud compute resources (AWS EC2 instances, OpenStack instances, etc.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*HVEwZ3xxd2GGeDfIi4Ycxg.png" /></figure><p>When I first began experimenting with these tools, I struggled to understand how they all worked together. Let’s set it up step by step.</p><h3>Create your Jenkins agents</h3><p>Jenkins can coordinate tasks across different agents, so you’ll need to create some virtual machines and add them as Jenkins nodes.</p><h4>Set up your VMs</h4><p>You’ll need to fire up some instances on your preferred cloud provider. Launch an instance, and in your preferred way (ssh, PuTTY, etc.), make sure you install at least these requirements on your instances:</p><p>• <a href="https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html">Node and npm</a> (Required by Cypress and likely your project)<br>• <a href="https://www3.ntu.edu.sg/home/ehchua/programming/howto/JDK_Howto.html">Java (required by Jenkins)</a><br>• <a href="https://docs.cypress.io/guides/getting-started/installing-cypress#System-requirements">Requirements for Cypress</a><br>• Any other system requirements your project needs to run</p><p>I recommend setting up one instance with all your needs, then creating a snapshot of that instance. You can launch more instances from that snapshot, making the creation of new Jenkins agents very quick.</p><h4>Add your VMs to Jenkins as Nodes</h4><p>Now that your VMs are ready, add them to Jenkins as Nodes. For a quick read on how to do that, check out this tutorial:</p><p><a href="https://www.jenkins.io/doc/book/using/using-agents/">Using Jenkins agents</a></p><h3>Set up Sorry-Cypress</h3><p><a href="https://docs.cypress.io/guides/guides/parallelization">Cypress.io’s documentation</a> explains that to run cypress tests in parallel, all you have to do is run the command:</p><pre>cypress run --record --key=abc123 --parallel</pre><p>What’s implied (poorly) is that this requires use of the Cypress.io dashboard service. This is a paid service, and it requires uploading your project’s code to a third party cloud service. If this doesn’t work for you, <a href="https://docs.sorry-cypress.dev/">Sorry-Cypress</a> to the rescue! Sorry-Cypress allows you to host a Cypress dashboard on your own cloud services and use it to coordinate parallel cypress testing. For the cloud-based approach that we are taking, here are a few quick setup steps:</p><ol><li>Create a new cloud instance that will be the dedicated to running the Sorry-Cypress suite of applications. Note this will not necessarily require the same boilerplate installations as your other instances. It will <em>not</em> be used as a Jenkins agent, but your Jenkins agents and the Sorry-Cypress instance must be able to communicate via http.</li><li>Install docker and docker-compose on your Sorry-Cypress instance. Once installed, its a breeze to install and run the entire Sorry-Cypress suite of applications using <a href="https://docs.sorry-cypress.dev/guide/dashboard-and-api">their docker-compose script</a>.</li></ol><p>Now you have your own sorry-cypress dashboard running on your own cloud resources. To check it, navigate to your-sorry-cypress-instance-ip:8080, and you’ll see your dashboard.</p><h3>Utilizing Sorry-Cypress</h3><p>In order to get your project to actually <em>use</em> sorry cypress, you’ll need to make some small changes. In your cypress.json, add a projectId of sorry-cypress :</p><pre>// cypress.json:</pre><pre>{<br>  &quot;baseUrl&quot;: &quot;http://localhost:3000&quot;,<br>  &quot;projectId&quot;: &quot;sorry-cypress&quot;,<br>  ...otherOptions<br>}</pre><p>You’ll also want to install <a href="https://www.npmjs.com/package/cy2">cy2</a> in your project, which will help guide cypress towards your custom cypress dashboard URL. For more details, see the full Sorry-Cypress Documentation:</p><p><a href="https://docs.sorry-cypress.dev/">Documentation</a></p><h3>Setting up Parallelization in Jenkins</h3><p>Now that all the pieces are in place, its time to orchestrate them with Jenkins. Let’s say we created 3 instances to be used as Jenkins agents, named “agent-1”, “agent-2”, and “agent-3”. We tell Jenkins to run cypress in parallel across these agents in a pipeline script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/991d2556cf0e12b9edd73764c5ad4846/href">https://medium.com/media/991d2556cf0e12b9edd73764c5ad4846/href</a></iframe><p>You can see that each parallel stage is running the same steps, but on a different node. Let’s break down what steps are being run:</p><ul><li>npm install --silent — install the project on the agent</li><li>npm start &amp; npx wait-on http://localhost:3000 — starts the project and waits for it to be available on port 3000 (your particular project may differ)</li></ul><p>The third command is more complicated, so let’s break that down further:</p><ul><li>CYPRESS_API_URL=\&quot;http:Sorry-Cypress-Instance-IP:1234/\&quot; — sets the cypress api url environment variable to our personal sorry-cypress directory url. Use your Sorry-Cypress instance IP of course</li><li>cy2 — a cy alternative that utilizes the CYPRESS_API_URL environment variable</li><li>run --record --key XXX --parallel — the standard cypress parallelization command — the key can be anything, sorry-cypress does not actually use it</li><li>--ci-build-id env.BUILD_ID — all parallel stages will use the same BUILD_ID , which allows the Sorry-Cypress director to associate the different parallel stages with the same build and not repeat the same tests across nodes</li></ul><p>Now when your Jenkins job runs, it will run cypress tests in parallel across as many nodes as you define. Let’s revisualize all our pieces in a more organized fashion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*BIZrFch6R8yCI_jgGAdU_A.png" /></figure><h3>Conclusion</h3><p>Cypress tests are a great way to make sure your UI behaves as expected, but testing cake take time and slow down your dev process. If you’ve got cloud resources, use them. With a careful orchestration of resources using Jenkins, you can cut down your testing time significantly.</p><h3>More Resources:</h3><ul><li><a href="https://docs.cypress.io/guides/guides/parallelization#Overview">Parallelization | Cypress Documentation</a></li><li><a href="https://medium.com/@adityahbk/cypress-parallelization-on-jenkins-using-sorry-cypress-197a86ad8ed1">Cypress Parallelization on Jenkins using Sorry-Cypress</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8241331fe50f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/parallelizing-cypress-with-jenkins-aws-and-sorry-cypress-8241331fe50f">Parallelizing Cypress with Jenkins, AWS, and Sorry-Cypress</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>