<?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"><channel><title><![CDATA[Platformatic Blog]]></title><description><![CDATA[Platformatic Blog]]></description><link>https://blog.platformatic.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1727183405468/9f1d8161-aee0-4422-af77-111e9ea87aef.png</url><title>Platformatic Blog</title><link>https://blog.platformatic.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 05:23:21 GMT</lastBuildDate><atom:link href="https://blog.platformatic.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[sqlite-js-stream: Litestream, rewritten for Node]]></title><description><![CDATA[Discover sqlite-js-stream, a TypeScript port of Litestream for Node.js that streams SQLite backups with bounded memory and S3 replication support.]]></description><link>https://blog.platformatic.dev/sqlite-js-stream-litestream-nodejs</link><guid isPermaLink="true">https://blog.platformatic.dev/sqlite-js-stream-litestream-nodejs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[SQLite]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[database]]></category><category><![CDATA[Data Backup]]></category><category><![CDATA[AI]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Tue, 20 Oct 2026 14:49:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/e0e79be7-4237-4604-8550-bcc26cc23fe2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>SQLite is the most widely used database in the world, but it only runs on a single machine. If that machine fails, your database is lost. Unlike Postgres, you can't solve this with traditional replication, because SQLite is just a file. You're replicating data, not a server.</p>
<p><a href="https://github.com/benbjohnson/litestream">Litestream</a> addresses this by streaming the WAL into unchangeable <a href="https://github.com/superfly/ltx">LTX</a> files on S3 or a local folder, and then restoring from those files. It's a well-designed tool written in Go. However, Platformatic's stack is built on Node.</p>
<p><a href="https://github.com/platformatic/sqlite-js-stream">sqlite-js-stream</a> is a TypeScript version of Litestream that runs directly on Node. It uses the built-in <code>node:sqlite</code> and Node's native type stripping, so there's no need for a build step.</p>
<p>To be clear about how this was built: the <strong>entire port was written by an AI coding agent called pi, running a DeepSeek V4 Flash vision model on two NVIDIA DGX Spark machines. There was n</strong>o cloud cluster, no massive GPU farm, no cloud model, and no one watching over every line. The design was based on Litestream and rewritten in TypeScript, with a human responsible for the architecture, reviews, and key decisions. The AI sped up the coding, but didn't replace human judgment. Details about the model, how it was used, and its mistakes are covered in <a href="https://github.com/platformatic/blog-posts/blob/1c456cc469d4417449358c7d76a3b15331a2671d/sqlite-js-stream/post.md#the-ai-part--what-it-actually-got-us">The AI part</a> below.</p>
<hr />
<h2><strong>The real win is distribution</strong></h2>
<p>Litestream is a Go binary. You install it, run it as a separate process alongside your app, write a config file, point it to the database and the storage bucket, and keep that binary updated with every deployment. This adds real operational overhead, and it's the main reason SQLite isn't used more often in production.</p>
<p>A JavaScript version folds most of it away. It's a package:</p>
<pre><code class="language-plaintext">npm install sqlite-js-stream
</code></pre>
<p>It runs inside your main process, so there's no sidecar process to manage, no config file to keep up with, and no extra binary to version with your app. It works with your existing package manager, CI, bundler, and deployment pipeline. You can run it behind the app's event loop, in a worker thread, or in a serverless function. You deploy it just like any other part of your Node app.</p>
<p>That's what really matters. SQLite is the most widely used database, but the main reason people avoid it in production isn't the database itself; it's the risk of losing data. If the solution is to run a sidecar binary that needs constant attention, many teams just choose Postgres instead. But if the solution is as simple as adding one npm install to your existing app, SQLite becomes a practical default again, not just a toy.</p>
<p>This is Atwood's Law playing out in real time:</p>
<blockquote>
<p><em>Any application that can be written in JavaScript will eventually be written in JavaScript.</em> <a href="https://blog.codinghorror.com/the-principle-of-least-power/">Jeff Atwood</a>, 2007</p>
</blockquote>
<p>Litestream is one of the best Go tools out there, and Atwood's Law suggests it was never going to stay Go-only for long. The real reason is distribution: the JavaScript runtime reaches more people than a compiled binary ever could. That's why this port is important. It turns a genuinely useful tool into something anyone using Node can install and use with their existing SQLite database.</p>
<hr />
<h2><strong>Why this exists</strong></h2>
<p>Backing up a SQLite database is not a copy job. If you just <code>cp</code> the file while it is being written, you get a corrupt snapshot. The WAL makes it worse: committed writes might be in <code>-wal</code>, not in the main file, and they can be checkpointed and truncated at any time. To get a consistent backup, you need to understand the WAL and hold off checkpointing while you read.</p>
<p>Litestream solves this by turning the WAL into a sequence of LTX files, each one holding the pages changed in a single transaction. To restore, you just replay those files in order. It's a smart approach, and it's fully compatible with litestream's format. Files created by this tool can be read by litestream, and the other way around.</p>
<p>The layout on main:</p>
<pre><code class="language-plaintext">sqlite-js-stream        core library (root package, pnpm workspace)
packages/backend-s3     S3 upload strategy (replica client + S3Leaser)
</code></pre>
<hr />
<h2><strong>What's in the box</strong></h2>
<p>The API is deliberately driver-agnostic. You hand a Replica a database path and a replica client; it reads the DB and WAL straight from disk, so your app can use whatever SQLite driver it wants.</p>
<pre><code class="language-javascript">import { Replica, FileReplicaClient, FileLeaser } from '@platformatic/sqlite-js-stream'

const replica = new Replica('/data/app.db', new FileReplicaClient('/backups'))
replica.leaser = new FileLeaser('/backups') // only one host is the active writer

await replica.run({ intervalMs: 1000, signal })
</code></pre>
<p>What has landed so far:</p>
<ul>
<li><p><strong>Streaming, end to end.</strong> <code>sync()/snapshot()</code> read pages one at a time from a file handle and stream the encoded LTX straight to a temp file. Peak memory is bounded by one page buffer, not the database size. <code>restore()</code> overlays incremental files on a snapshot base without materializing the whole DB.</p>
</li>
<li><p><strong>The LTX format, faithfully.</strong> The port writes <code>superfly/ltx v0.5.2</code> at <code>ltx/{level}/{min}-{max}.ltx</code>, snapshots at level 9, with CRC-64 ISO checksums. Same bytes as litestream writes.</p>
</li>
<li><p><strong>Compaction + retention, matched to litestream.</strong> Per-level time-bucketed compaction (L1 every 30s, L2 every 5m, L3 every 1h), time-based snapshot retention, TXID-boundary cascade down the levels, and L0 time retention that never deletes the live head.</p>
</li>
<li><p><strong>Distributed leasing.</strong> A <code>Leaser</code> claims a <code>lock.json</code> lease; <code>run()</code> makes exactly one host the primary (writer) and the rest idle followers. On S3 it uses real <code>If-None-Match/If-Match</code> conditional writes, so two racy acquirers cannot both win. The lease is renewed on a dedicated timer, independent of the run-loop cadence.</p>
</li>
<li><p><strong>A pnpm monorepo.</strong> The core lives at the root; the S3 addon is a separate package under <code>packages/</code>.</p>
<hr />
<h2><strong>First numbers</strong></h2>
<p><code>sync()</code> / <code>restore()</code> have reproducible benchmarks in <a href="https://github.com/platformatic/sqlite-js-stream/blob/main/bench/bench-sync-restore.ts">bench/bench-sync-restore.ts</a>. These tests run on localhost with a file backend, no network involved, and use a small database (100,000 rows across 100 transactions, with a 3.76 MB WAL). The results show the tool works and that memory use is limited. This isn't a direct comparison with litestream, which is important to note.</p>
<pre><code class="language-plaintext">workload: rows=100000, batch=1000, transactions=100

sync():    wall ~180-250 ms    ~15-21 MB/s (WAL)    ~400-480k rows/s    peak RSS ~106 MB
restore(): wall ~330-360 ms    ~7-8 MB/s (DB)      ~280-300k rows/s    peak RSS ~114 MB
 integrity: ok, rows: 100000
</code></pre>
</li>
</ul>
<p>The number that matters is the memory one. Run it at two sizes with <code>SCALE=4</code> (which runs sync at 50k and 200k rows), and the WAL grows 4.1x while peak RSS moves 1.22x:</p>
<pre><code class="language-plaintext">rows=50000    WAL=1.87 MB   sync=140 ms   peak RSS=99.8 MB
rows=200000   WAL=7.72 MB   sync=542 ms   peak RSS=121.2 MB
WAL grew 4.1x; peak RSS grew 1.22x.
</code></pre>
<p>So the streaming claim is accurate: memory use is limited by a page buffer, not the size of the database. Peak RSS covers the whole process, including Node's baseline, so the key point is that memory stays flat as the database grows, not the exact value.</p>
<p>What this does <strong>not</strong> prove: it is not litestream performance, it is file-backend localhost, and it is a few-MB database. The real head-to-head needs the same workload run through the Go binary against the same target, and honestly, the pure-JS LZ4 codec is expected to lose to Go's SIMD <code>pierrec/lz4</code> on the decompress side. That's next on the list.</p>
<hr />
<h2><strong>Being honest about the limits</strong></h2>
<p>This is a <strong>disaster-recovery tool, not a distributed database.</strong> The lease elects a single writer to storage, but it does not merge, compare, or reconcile the data across hosts. If host A has <code>row id=1 → "X"</code> and host B has <code>row id=1 → "Y"</code> and they share one prefix, only the primary's value lands in S3. From the backup's perspective, the other is simply gone.</p>
<p>So, it's only safe to point several hosts at one prefix if they all have the same logical data, like a disaster recovery standby restored from the same backup. Different databases should use different prefixes. This warning is now in the README and the architecture documentation, because it's a real risk and no one should have to learn it the hard way.</p>
<p>There is also a genuine gap on failover: a standby host only contains data up to the last backup, not the last few seconds the primary wrote before it died. There is no way around that with a WAL-based replicator.</p>
<p>Status: early. Cloud backends beyond S3 (GCS, Azure, SFTP, NATS), VFS mirroring, and the IPC server are not implemented. The core package is not published yet.</p>
<hr />
<h2><strong>The AI part: what it actually achieved</strong></h2>
<p>This project was a real experiment in building a complex port using only an agent running on <strong>local models</strong>.</p>
<p>The model actually doing the work is <a href="https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-Vision-Exp">DeepSeek-V4-Flash-Vision-Exp</a>, DeepSeek's V4 Flash vision build, served with <a href="https://github.com/vllm-project/vllm">vLLM</a> using tensor parallelism (<code>TP=2</code>) across <strong>two NVIDIA DGX Spark</strong> machines. Each one is a GB10 Grace Blackwell with 128 GB of unified memory at 273 GB/s; two of them linked over ConnectX is how the model fits in local memory. It's an experimental local flash/vision build, not a cloud frontier model. The harness is pi, and a human wrote the PLAN, reviewed the diffs, and made the scope calls.</p>
<ul>
<li><p><strong>TDD kept it honest.</strong> Tests were written first, which is how the agent stayed on track. 121 tests now (103 core + 18 S3), all green under Node 24.</p>
</li>
<li><p><strong>The agent was good at the mechanical parts</strong>: reading the Go source, mirroring the compaction-level scheduling, getting the LTX encoder/decoder round-trip to pass, and standing up the monorepo + CI.</p>
</li>
<li><p><strong>The agent also went down a rabbit hole that had to be cancelled.</strong> At one point it started building a <em>legacy v0.3.x generation</em> restore path, a whole different LZ4 frame codec, on the instruction to "upgrade to the newer file format." That turned out to be a misunderstanding of the problem: the write format was already the modern LTX. The agent did the work, then a human looked at it and said no, that's backward-compat for reading old backups nobody needs. That path was cut. The architecture and the scope call were a human decision, not the model's.</p>
</li>
<li><p><strong>Local models were a constraint, not a badge.</strong> There was no cloud model to lean on. That meant more careful specs and more relying on the test suite, and it made the "no build step, run <code>.ts</code> directly" requirement real rather than aspirational.</p>
</li>
</ul>
<p>If you want to poke at how far this can go, clone the repo, read <code>PLAN.md</code> (it tracks every milestone and risk), run <code>pnpm test:all</code>, and try pointing a replica at your own database.</p>
<p>If you hit something: a format edge case, a compaction bug, an interop gap, open an issue. The hardest part of a project like this is the byte-for-byte LTX compatibility, and the gaps are better found with your database than in production.</p>
<p>SQLite's biggest weakness doesn't have to be limited to Go anymore. This version was written in Node.</p>
<p><em>Credit where it's due: the design, the LTX format, and most of the engineering reasoning come from</em> <a href="https://github.com/benbjohnson"><em>Ben Johnson</em></a><em>'s</em> <a href="https://github.com/benbjohnson/litestream"><em>Litestream</em></a> <em>and the</em> <a href="https://github.com/superfly/ltx"><em>superfly/ltx</em></a> <em>library. This is a port, and the original deserves the credit.</em></p>
]]></content:encoded></item><item><title><![CDATA[node:vfs: what actually landed]]></title><description><![CDATA[node:vfs in Node.js, with ZIP archives, module loading, native addons, FFI support, and single-executable applications using virtual filesystems.]]></description><link>https://blog.platformatic.dev/article-slug-node-vfs-nodejs-virtual-filesystem</link><guid isPermaLink="true">https://blog.platformatic.dev/article-slug-node-vfs-nodejs-virtual-filesystem</guid><category><![CDATA[Node.js]]></category><category><![CDATA[virtual file system]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Tue, 13 Oct 2026 16:59:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/a8b380cb-da91-4376-8ef5-92982c8bea3f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Node.js apps usually expect their files to be on disk. They import modules, read configuration, and open templates by path. This works fine until you want to package everything in a ZIP file, a single executable, or generate files in memory. Even if the data is available, your app and its dependencies won’t know how to access it.</p>
<p>A virtual filesystem (VFS) lets you organize those bytes into files and folders, even if they aren’t real files on disk. You can open paths, read contents, list directories, or check metadata. The storage provider decides where the data actually lives, maybe in memory, inside an archive, as part of an executable, or in a real directory shown under a different path.</p>
<p>In Node.js, a <code>VirtualFileSystem</code> combines the storage provider with an API similar to fs. You can use it as a private file tree, or you can mount it to give the tree a path that <code>node:fs</code> operations and module loaders recognize. This way, code that reads templates or imports modules can keep using the same APIs as before.</p>
<p>This is what makes VFS useful. Tests can create in-memory fixtures without dealing with temporary directories. Packaged apps can read bundled configuration files using <code>fs</code> instead of a special asset API. Generated JavaScript can import nearby modules without writing them to disk first. You get to decide how to store and distribute files, without needing to update every dependency.</p>
<p>In <a href="https://github.com/platformatic/blog-posts/blob/91428d2770f749822a5067d2ce29705493957a83/node-vfs/blog.md">our first VFS article</a>, we talked about the <a href="https://github.com/nodejs/node/pull/61478">original node:vfs proposal (PR #61478)</a> and our userland implementation. Now, core support has landed, with a new mount model and support for ZIP archives, native addons, and shared-library loading using <code>node:ffi</code>.</p>
<p>The first version of node:vfs shipped in <a href="https://nodejs.org/en/blog/release/v26.4.0">Node.js 26.4.0</a>. <a href="https://nodejs.org/en/blog/release/v26.9.0">Node.js 26.9.0</a> added module-loader integration, the ZIP provider, native-addon loading, and Single Executable Application support. <a href="https://nodejs.org/en/blog/release/v26.10.0">Node.js 26.10.0</a> added VFS-backed FFI and startup flags for mounting and running from a VFS. The examples below use 26.10.0 as the baseline. VFS is still experimental and requires <code>--experimental-vfs.</code></p>
<hr />
<h2><strong>Start with the code</strong></h2>
<p>Save this as <code>example.mjs</code>:</p>
<pre><code class="language-javascript">import { create } from 'node:vfs'
import { readFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'

using app = create()

app.writeFileSync('/config.json', '{"name":"VFS"}')
app.writeFileSync('/greet.cjs', 'module.exports = name =&gt; `Hello, ${name}!`')
app.writeFileSync(
 '/main.mjs',
 `
import greet from './greet.cjs'
import { readFileSync } from 'node:fs'

const config = JSON.parse(
 readFileSync(new URL('./config.json', import.meta.url), 'utf8')
)

export default greet(config.name)
`
)

const root = app.mount()

console.log(readFileSync(join(root, 'config.json'), 'utf8'))
console.log(await readFile(join(root, 'config.json'), 'utf8'))

const { default: greeting } = await import(`${app.mountPointURL}/main.mjs`)
console.log(greeting) // Hello, VFS!
</code></pre>
<p>Run it with:</p>
<pre><code class="language-plaintext">node --experimental-vfs example.mjs
</code></pre>
<p>There are two namespaces in this setup. Before mounting, <code>/config.json</code> is just a path inside the private VFS instance. After mounting, regular <code>node:fs</code> calls can access that file through the returned <code>root</code>. The VFS instance’s own methods also expect mounted paths, so fill it with files before mounting, or use the returned root after.</p>
<p>The module inside the VFS uses a normal relative import and reads a file relative to <code>import.meta.url.</code> It doesn’t import <code>node:vfs</code>. Your application code shouldn’t need to know which provider stores its files.</p>
<p>Notice that we imported <code>readFileSync</code> before mounting. It still works. Core dispatches from inside the filesystem functions rather than replacing their public exports, so a dependency that captured a function reference earlier doesn't bypass the VFS.</p>
<p><code>mountPointURL</code> is a <code>file:URL</code> string. Use it for dynamic imports instead of passing a platform-specific path, especially on Windows. The <code>using</code> declaration will unmount the instance when its scope ends.</p>
<hr />
<h2><strong>Why you no longer choose the mount point</strong></h2>
<p>The original article showed this:</p>
<pre><code class="language-plaintext">myVfs.mount('/virtual')
</code></pre>
<p>It also showed an overlay mounted at <code>/</code>, where virtual files took precedence, and missing files fell through to disk.</p>
<p>That is not the current core API. <code>mount()</code> takes no target and returns a path chosen by Node.js. Each instance gets its own reserved namespace, which cannot overlap another instance's mount or a real directory.</p>
<p>On POSIX systems, the current implementation uses paths shaped like <code>/dev/null/vfs/0</code>. That looks odd until you consider the reason: <code>/dev/null</code> is a device, not a directory. It cannot have real child files. Windows uses the corresponding null-device namespace. This is an implementation detail, not a path format to build into your application. Always use the value returned by <code>mount()</code>or the <code>mountPoint</code> and <code>mountPointURL</code> properties.</p>
<p>This change removes a whole set of questions from the resolution process. Does the virtual file take priority? Should we check the disk if it’s missing? What if one mount overlaps another?</p>
<p>A path under a mount belongs to that VFS. If the file isn’t there, it’s just missing; there’s no fallback to the disk for that path.</p>
<p>It also changes the testing story. You can give a library a virtual directory containing its fixtures, but you cannot use core VFS to silently replace <code>/etc/config.json</code> while leaving the rest of <code>/etc</code> alone. Code with hard-coded real paths needs a configurable path or a different testing technique.</p>
<p>We think this constraint is better. Mounting an application package shouldn’t change what an unrelated real path means elsewhere in the process.</p>
<hr />
<h2><strong>The resolver stays the resolver</strong></h2>
<p>The tricky part of loading code from a virtual filesystem isn’t reading the JavaScript bytes. It’s figuring out all the questions that come before that step.</p>
<p>Which <code>package.json</code> applies? Is this <code>.js</code> file CommonJS or ESM? What does the package's <code>exports</code> field allow? Where should a bare package specifier look for <code>node_modules</code>?</p>
<p>The <a href="https://github.com/nodejs/node/pull/63653">core integration</a> sends the filesystem operations used by Node.js’s resolution algorithms to the right VFS. It doesn’t add a new package-resolution algorithm for virtual files. Package metadata is still handled by Node.js’s package JSON system.</p>
<p>The mount acts as a resolution root. Package-scope searches and the ordinary upward search through <code>node_modules</code> stop there. A package's module type won't accidentally come from a <code>package.json</code> above the virtual mount.</p>
<p>That needs a qualification: CommonJS still has its legacy global lookup paths, including <code>NODE_PATH</code>. And absolute specifiers can cross between virtual and real files. A module in a VFS can load real code, just as real code can load a virtual module. This is a resolution boundary, not an execution boundary.</p>
<p>Module identity works the way you'd expect. <code>__filename</code> and <code>__dirname</code> refer to mounted paths; <code>import.meta.url</code> refers to the corresponding file URL. Repeated loads are cached.</p>
<p>Unmounting clears loader-cache entries associated with that mount, including CommonJS modules, ESM load-cache entries, and package metadata. It leaves other mounts and real-filesystem modules alone. If you unmount, change the files, and remount, a new load can see the new code.</p>
<p>Unmounting doesn’t stop code that’s already running. References to functions you imported earlier still work. Timers keep running. Unmounting isn’t the same as shutting down the app, and changing a file while it’s mounted doesn’t trigger an automatic hot reload.</p>
<hr />
<h2><strong>Providers describe storage, not isolation</strong></h2>
<p>The public API still has the same basic split: <code>VirtualFileSystem</code> supplies the <code>fs-</code>like interface, and a provider supplies storage operations.</p>
<p>The built-in public providers are:</p>
<table style="min-width:481px"><colgroup><col style="min-width:25px"></col><col style="width:456px"></col></colgroup><tbody><tr><td><p><code>MemoryProvider</code></p></td><td><p>A writable in-memory tree, with symlinks and watching. This is the default.</p></td></tr><tr><td><p><code>RealFSProvider</code></p></td><td><p>Files in a real directory, mapped into the VFS namespace.</p></td></tr><tr><td><p><code>ZipProvider</code></p></td><td><p>Entries in a <code>node:zlib</code>, <code>ZipBuffer</code> or <code>ZipFile</code>.</p></td></tr></tbody></table>

<p><code>VirtualProvider</code> is the base class for custom implementations. It provides derived operations on top of primitives such as opening files and reading directory entries. Capabilities such as read-only storage, symlinks, and watching belong to the provider.</p>
<p>There are synchronous, callback, and promise-based APIs, plus streams and file handles. That familiar shape matters for compatibility, but it doesn't mean every backend can implement every filesystem operation. For example, the ZIP provider in 26.10.0 does not support recursive <code>readdir</code>, symlinks, or watching. Treat provider capabilities as part of your application's requirements.</p>
<p><code>RealFSProvider</code> is now in core; the first article described it as a userland addition. <code>SqliteProvider</code> isn't a core export. The SEA provider is internal, used by Node.js when starting an executable with VFS-enabled assets, rather than a public <code>SEAProvider</code> constructor.</p>
<hr />
<h3><strong>Create a compressed ZIP, then mount it</strong></h3>
<p>You can build the archive with Node.js itself. The experimental <a href="https://nodejs.org/docs/v26.10.0/api/zlib.html#zlibcreateziparchiveentries-options">ZIP API in node:zlib</a> creates ZIP entries and writes them into an archive. This is different from gzipping a file: a ZIP contains named entries that the VFS can expose as a directory tree.</p>
<p>Suppose your application has <code>app/main.mjs, app/config.json</code>, and <code>app/package.json</code> with <code>{"main":"./main.mjs"}</code> so the startup loader can find its entry point. Save this as <code>pack.mjs</code>:</p>
<pre><code class="language-javascript">import { createWriteStream } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { pipeline } from 'node:stream/promises'
import { ZipEntry, createZipArchive } from 'node:zlib'

const entries = []

for (const name of ['main.mjs', 'config.json', 'package.json']) {
 const contents = await readFile(`./app/${name}`)
 entries.push(await ZipEntry.create(name, contents, { method: 'deflate' }))
}

await pipeline(createZipArchive(entries), createWriteStream('./app.zip'))
</code></pre>
<p>Run <code>node pack.mjs</code>. The archive contains <code>main.mjs</code>, <code>config.json</code>, and <code>package.json</code> at its root, not under an extra app directory. Include every module, package manifest, and asset your application needs; this script isn't a dependency bundler.</p>
<p>Compression is selected per entry. <code>'deflate'</code> is the default and a good choice when you want compatibility with other ZIP tools. Use <code>'store'</code> to leave an entry uncompressed, which can make sense for already-compressed assets. <code>'zstd'</code> is also supported, but check that any other tools consuming the archive support Zstandard-compressed ZIP entries. <code>ZipEntry.create()</code> keeps an entry uncompressed if compression wouldn't reduce its size.</p>
<p>This example reads each input file into memory. For large files, <code>ZipEntry.createStream()</code> can instead take a <code>createReadStream()</code> source and compress it as <code>createZipArchive()</code> writes the archive. On the reading side, <code>ZipProvider</code> handles decompression; application code just reads files normally.</p>
<p>Now mount the resulting archive and import its entry point:</p>
<pre><code class="language-javascript">import { create, ZipProvider } from 'node:vfs'
import { ZipFile } from 'node:zlib'

using archive = ZipFile.openSync('./app.zip')
using app = create(new ZipProvider(archive))

app.mount()
await import(`${app.mountPointURL}/main.mjs`)
</code></pre>
<p>You can read JavaScript and assets directly from the archive without extracting the app into a directory first. Native binaries use a different loading method, which I’ll explain next.</p>
<p>The archive is read-only by default. A <code>ZipFile</code> opened with <code>{ writable: true }</code> can be modified; an in-memory <code>ZipBuffer</code> is writable. Writes through an open VFS file handle commit a new archive entry when that handle closes. A ZIP member isn't an ordinary disk file that can be edited in place.</p>
<p>Synchronous reads may include decompression, and synchronous writes may include compression. These operations block the event loop. Packaging your app in a ZIP is handy, but it doesn’t guarantee faster startup.</p>
<p>There are two lifetimes in this example. Disposing <code>app</code> unmounts it, and disposing <code>archive</code> closes the underlying archive. The declarations are set up so the VFS unmounts before the archive closes.</p>
<hr />
<h2><strong>A correction: this is not a sandbox</strong></h2>
<p>In the first article, we described <code>RealFSProvider</code> as sandboxed filesystem access and suggested VFS for multi-tenant sandboxing. That wording was wrong.</p>
<p><code>RealFSProvider</code> maps paths under a configured root and rejects paths and symlinks that resolve outside it. Those checks do not turn it into a security boundary. Mounting a VFS doesn't stop code from accessing other real paths, spawning processes, or using other capabilities available to the Node.js process.</p>
<p>The same goes for generated code. Importing an AI-generated module from memory is convenient, but it doesn’t make running it safe.</p>
<p>The <a href="https://nodejs.org/docs/v26.10.0/api/vfs.html#security">VFS security documentation</a> is explicit: this is not a sandbox, permission system, or access-control mechanism. Untrusted code needs an appropriate isolation boundary, such as an operating-system sandbox or a separately isolated process.</p>
<p>When Node.js's Permission Model is enabled, mounting is disabled unless you explicitly pass <code>--allow-fs-vfs</code>. That is permission to use the mounting mechanism, not a promise of tenant isolation.</p>
<hr />
<h2><strong>Single executables can use ordinary file access</strong></h2>
<p>Single Executable Applications were one of the main reasons for this work. Embedding an asset is only part of the solution; the app still expects to read it using <code>fs</code>.</p>
<p>With <a href="https://nodejs.org/docs/v26.10.0/api/single-executable-applications.html#virtual-file-system-vfs-for-assets">"useVfs": true</a>, Node.js mounts the bundled assets as a read-only VFS and runs the main script from inside it. Both CommonJS and ESM entry points are supported.</p>
<p>For example, a SEA configuration can include:</p>
<pre><code class="language-javascript">{
 "main": "main.mjs",
 "mainFormat": "module",
 "output": "app.blob",
 "useVfs": true,
 "assets": {
   "config.json": "config.json",
   "greet.mjs": "greet.mjs"
 }
}
The main module can then use:
import { readFileSync } from 'node:fs'
import { greet } from './greet.mjs'

const config = JSON.parse(readFileSync(new URL('./config.json', import.meta.url), 'utf8'))

console.log(greet(config.name))
</code></pre>
<p>The asset keys set the paths inside the virtual tree. You can include dependencies under <code>node_modules</code>, along with their package metadata. VFS doesn’t gather these dependencies for you; you still need to package all the files your app uses.</p>
<p>CommonJS code uses <code>__dirname</code>-relative paths instead. Either way, the application doesn't need a hard-coded mount point or a separate asset-access API.</p>
<p>There is a real trade-off: useVfs cannot currently be combined with <code>useSnapshot</code> or <code>useCodeCache</code>. If startup time is your priority, don't assume that preserving an unbundled module tree will beat a bundled application. Measure your workload.</p>
<hr />
<h3><strong>Native addons need help from the operating system</strong></h3>
<p>The first article said core could support native addons where userland couldn't. <a href="https://github.com/nodejs/node/pull/65680">That support has now landed</a>.</p>
<p>You can <code>require()</code> a <code>.node</code> file stored in a mounted VFS. But the operating system's dynamic loader still cannot open a virtual path. Node.js reads the bytes and creates a private, self-cleaning image that the loader can use.</p>
<p>On Linux, it uses an anonymous in-memory file descriptor. Other platforms use temporary files. That’s why you shouldn’t claim that loading an app from a VFS “never touches disk” for every provider and platform.</p>
<p>Native binaries still have to match the target platform and ABI. VFS only changes how the bytes get to the loader, not the compatibility requirements.</p>
<hr />
<h2><strong>Shared libraries through node:ffi</strong></h2>
<p>Native addons aren't the only way to call native code. Node.js's Foreign Function Interface, <code>node:ffi</code>, lets JavaScript open a shared library and call exported functions by describing their argument and return types. The library doesn't need to implement the Node.js addon API; it needs a compatible C ABI.</p>
<p>The <a href="https://github.com/nodejs/node/pull/65909">VFS integration for FFI</a> lets both <code>ffi.dlopen()</code> and <code>new ffi.DynamicLibrary()</code> open libraries from mounted paths. This support arrived in Node.js 26.10.0, after the .nodeaddon support in 26.9.0. The following example needs a 26.10.0 build with <code>node:ffi</code> available.</p>
<p>Suppose <code>app.zip</code> contains a <code>native</code> directory with a library named <code>libmath.dylib</code>, <code>libmath.so</code>, or <code>libmath.dll</code>, depending on the target platform. It exports <code>int32_t</code> <code>add_i32(int32_t, int32_t)</code>. We can load it straight from the mounted archive:</p>
<pre><code class="language-javascript">import { create, ZipProvider } from 'node:vfs'
import { ZipFile } from 'node:zlib'
import { dlopen, suffix } from 'node:ffi'
import { join } from 'node:path'

using archive = ZipFile.openSync('./app.zip')
using app = create(new ZipProvider(archive))

const root = app.mount()
const { lib, functions } = dlopen(join(root, 'native', `libmath.${suffix}`), {
 add_i32: { arguments: ['int32', 'int32'], return: 'int32' }
})

try {
 console.log(functions.add_i32(20, 22)) // 42
 console.log(lib.path) // The mounted virtual path
} finally {
 lib.close()
}
</code></pre>
<p>This uses the same private-image method as native addons. Node.js reads the library’s bytes from the provider and makes them available to the OS’s dynamic loader. <code>lib.path</code> still shows the virtual path, not the temporary image’s location. Libraries opened from real paths still load directly.</p>
<p>This means a package can include its JavaScript, assets, and a native library together, without needing custom extraction code. You still need a binary for the right OS and architecture, correct function signatures, and any native dependencies the OS needs. VFS doesn’t make a shared library portable.</p>
<p>The library also has its own lifetime. Unmounting the VFS doesn't unload a library you've already opened; close the library when you're finished with it. In this example, <code>finally</code> closes it before the <code>using</code> declarations unmount the VFS and close the archive. Under the Permission Model, native calls also require <code>--allow-ffi</code>, separately from the VFS mounting permission.</p>
<hr />
<h2><strong>Mount before the application starts</strong></h2>
<p>The examples so far need a bootstrap script to create and mount the VFS. Node.js 26.10.0 also includes <a href="https://github.com/nodejs/node/pull/65748">startup flags contributed by Philipp Dunkel</a>:</p>
<pre><code class="language-plaintext">node --experimental-vfs --vfs-load=app.zip
</code></pre>
<p>This command works on Node.js 26.10.0 or later; the flags are not available in 26.9.0.</p>
<p><code>--vfs-load</code> mounts the source and runs its entry point. It uses the mount's <code>package.jsonmain</code> field or <code>index.js</code>, much like running a directory. <code>--vfs-mount</code> mounts a source without selecting it as the entry point. Multiple mounts remain separate trees; they aren't an overlay or a merged dependency directory.</p>
<p>Directories use <code>RealFSProvider</code>. ZIP archives use <code>ZipProvider</code>, selected from their contents rather than their filename extension.</p>
<p>The same change adds <code>registerProvider({ name, canHandle, create })</code>. A module preloaded with <code>--require</code> or <code>--importcan</code> register another format before startup mounts are created. Registered providers are checked before the built-ins, newest registration first. This lets custom packaging formats participate without teaching core about every format.</p>
<hr />
<h2><strong>What this means for the original proposal</strong></h2>
<p>The first article promised a one-line migration from <code>@platformatic/vfs</code> to <code>node:vfs</code>. Given how the core design evolved, that promise was too broad.</p>
<p>We've just released <a href="https://www.npmjs.com/package/@platformatic/vfs">@platformatic/vfsv0.5.0</a> with compatibility for the new mount API: <code>mount()</code> takes no prefix and returns an isolated path, and <code>mountPointURL</code> provides its file URL. This lets code use the same mount pattern on Node.js 22+, but the userland shim still cannot provide core's ZIP provider, SEA integration, or native-addon loading.</p>
<p>If your code picks mount points, relies on overlays, or uses a provider that core doesn’t export, just swapping the import isn’t enough. Build your app around the returned mount path, use relative paths, and check which provider features you really need. The original <code>process</code> mount-event examples aren’t part of the current core API either.</p>
<p>The good news is that the useful part remains: regular application code can read files and resolve modules from different storage providers. The rule against shadowing real paths makes this behavior easier to understand.</p>
<p>James Snell co-authored the module-loader integration. Philipp Dunkel contributed the ZIP provider, native-addon loading, and startup flags. The landed changes also carry review from Paolo Insogna, Stephen Belanger, and other Node.js collaborators. This work became much more than the original holiday prototype.</p>
<p>Try the first example on Node.js 26.10.0 or a newer version with the right APIs. Then test a small, trusted module tree from your own app. If any supported filesystem operation or resolution works differently from disk, <a href="https://github.com/nodejs/node/issues">report it with a reproducible example.</a></p>
]]></content:encoded></item><item><title><![CDATA[Renewing Our Open Source Pledge for 2026]]></title><description><![CDATA[Platformatic renews its Open Source Pledge for 2026 with $13,000 in contributions, Node.js VFS work, and ongoing open source security support.]]></description><link>https://blog.platformatic.dev/renewing-open-source-pledge-2026</link><guid isPermaLink="true">https://blog.platformatic.dev/renewing-open-source-pledge-2026</guid><category><![CDATA[Open Source]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[fastify]]></category><category><![CDATA[Security]]></category><category><![CDATA[platformatic]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Wed, 30 Sep 2026 14:39:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/2ead8237-b826-4082-a198-d679063d4594.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Platformatic is renewing its <a href="https://opensourcepledge.com/">Open Source Pledge</a> for 2026. This year, we’re reporting <strong>six developers and $13,000 in financial contributions</strong> to the foundations and maintainers supporting our ecosystem.</p>
<p>Our commitment also includes the time we spend building and maintaining open source software. In 2026, that has included contributing a virtual file system to Node.js and helping the OpenJS Foundation, Node.js, and Fastify handle a growing volume of security reports.</p>
<p>The pledge asks companies to contribute at least <a href="https://opensourcepledge.com/about/">$2,000 per full-time equivalent developer each year</a>. For our six developers, that means a minimum of $12,000.</p>
<p>We’re continuing our support for the following organizations and maintainers:</p>
<table style="width:669px"><colgroup><col style="width:409px"></col><col style="width:260px"></col></colgroup><tbody><tr><td><p><strong>Recipient</strong></p></td><td><p><strong>Contribution</strong></p></td></tr><tr><td><p>OpenJS Foundation</p></td><td><p>$5,000</p></td></tr><tr><td><p>Linux Foundation</p></td><td><p>$5,000</p></td></tr><tr><td><p>GraphQL Foundation</p></td><td><p>$2,000</p></td></tr><tr><td><p>OpenAPI Initiative</p></td><td><p>$500</p></td></tr><tr><td><p>Forbes Lindesay</p></td><td><p>$500</p></td></tr><tr><td><p><strong>Total</strong></p></td><td><p><strong>$13,000</strong></p></td></tr></tbody></table>

<p>That puts our contribution at approximately <strong>$2,167 per developer</strong>. Our engineering and maintenance work comes in addition to these payments.</p>
<p>Earlier this year, we contributed the implementation of a virtual file system to Node.js. We wrote about the motivation in <a href="https://blog.platformatic.dev/why-nodejs-needs-a-virtual-file-system">Why Node.js needs a virtual file system</a>: applications should be able to work with virtual files through familiar filesystem APIs, including loading modules without first writing them to disk.</p>
<p>The work began with <a href="https://github.com/nodejs/node/pull/61478">the original VFS proposal</a> and landed in smaller pieces:</p>
<ul>
<li><p><a href="https://github.com/nodejs/node/pull/63115">The experimental node:vfs subsystem</a>, providing the core abstractions and storage providers.</p>
</li>
<li><p><a href="https://github.com/nodejs/node/pull/63537">Integration with Node.js filesystem APIs</a>, allowing ordinary file operations to reach mounted virtual filesystems.</p>
</li>
<li><p><a href="https://github.com/nodejs/node/pull/63653">CommonJS and ES module loader integration</a>, enabling <code>require()</code> and <code>import</code> to load virtual files.</p>
</li>
<li><p><a href="https://github.com/nodejs/node/pull/65675">Single Executable Application integration</a>, making bundled assets accessible through the filesystem.</p>
</li>
</ul>
<p>These changes create new possibilities for packaging applications and loading code from memory. The implementation remains experimental, and getting it into core has depended on the work of reviewers and contributors across the Node.js community.</p>
<p>Another substantial part of our contribution this year has been security triage.</p>
<p>In <a href="https://adventures.nodeland.dev/archive/triaging-the-ai-horde/">Triaging the AI Horde</a>, Matteo described receiving 20–40 security reports a week, almost all of them AI-written. Some identify real problems. Others are duplicates, false positives, or reports about behaviour outside a project’s threat model. Sorting them takes time and judgment.</p>
<p>Platformatic has supported the OpenJS Foundation, Node.js, and Fastify in handling this workload. That means spending maintainer time assessing reports, separating actionable issues from noise, and explaining why a reported behaviour does or does not constitute a vulnerability.</p>
<p>This work rarely produces an announcement. A carefully assessed report may end with an explanation and no code change. It still matters: maintainers need room to address real vulnerabilities, work with researchers, and keep their projects moving without burning out.</p>
<p>Our experience this year has reinforced why we make this pledge. Open source needs sustained funding and people who have time to do the work, from implementing new capabilities to reviewing security reports.</p>
<p>If your company depends on open source, we encourage you to <a href="https://opensourcepledge.com/">join the Open Source Pledge</a>. Budget for the software you rely on, support its maintainers, and make that support a recurring commitment.</p>
<p>Thank you to the maintainers, reviewers, researchers, and contributors working alongside us.</p>
]]></content:encoded></item><item><title><![CDATA[More threads on an already busy machine]]></title><description><![CDATA[v]]></description><link>https://blog.platformatic.dev/more-threads-on-an-already-busy-machine</link><guid isPermaLink="true">https://blog.platformatic.dev/more-threads-on-an-already-busy-machine</guid><category><![CDATA[Node.js]]></category><category><![CDATA[thread]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[performance]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[cpu]]></category><category><![CDATA[Linux]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Thu, 24 Sep 2026 14:46:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/c8b5bdd9-efee-4be0-9dd0-025b81762109.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The bcrypt numbers in <a href="https://github.com/nubjs/nub/pull/919">Nub’s thread-pool PR</a> make a good case for increasing the pool on the machines tested. The part I disagree with is choosing that setting for every application from its CPU count. Before starting more work, we need to know what else is using the machine.</p>
<hr />
<h2><strong>“available” does not mean free</strong></h2>
<p>Suppose a process reports sixteen through <code>os.availableParallelism()</code>. Those CPUs could already be busy running other applications. The function estimates how much parallelism the process can use under the OS constraints; it doesn’t check whether the CPUs are idle. Nub uses Rust’s <code>available_parallelism</code>, with the same limitation.</p>
<p>Now let several processes make that sizing decision. Each sees sixteen, each starts its workers, and all of them compete for the same CPU time. There’s no reservation attached to the number sixteen.</p>
<p>For bcrypt, this matters immediately. On a machine with no spare CPU capacity, twelve more compression or hashing jobs have to take time from something already running. That includes the event loop. Jobs can take longer to finish, and context switches and cache contention can reduce overall throughput. The closing comment on <a href="https://github.com/nodejs/node/pull/61533#issuecomment-5244734518">Node.js PR #61533</a> gives this as the objection to automatic sizing.</p>
<hr />
<h2><strong>Nice is slow</strong></h2>
<p>Nub lowers the priority of Linux workers beyond the first four to nice 10. Its busy-host measurements show much less interference with neighbouring processes after that change. That’s useful.</p>
<p>But nice 10 isn’t an instruction to wait for an idle CPU. The scheduler still gives those workers a share of CPU time when the host is busy. Their jobs also retain memory and compete for caches and memory bandwidth.</p>
<p>There’s a cost on the request side, too. Say a bcrypt job has started on one of the lower-priority workers. If that worker gets less CPU time, the request may wait longer. Freeing another worker won’t move the running job over to it. Protecting the neighbours can therefore come at the expense of completion latency for those requests.</p>
<hr />
<h2><strong>One vCPU, four workers</strong></h2>
<p>There’s an important correction for small containers: Nub doesn’t set the pool size to ten. Ten is the Linux nice value for workers added beyond the original four. If Nub correctly detects one vCPU or less, it leaves you with four workers at their original priority, just as Node does. That can still be too much concurrent hashing for the container’s CPU allowance.</p>
<p>The <a href="https://github.com/platformatic/gzip-eval-async">one-CPU gzip test</a> gives a concrete example. For 2 MiB inputs with an 8:1 compression target, one async worker and one outstanding job delivered 49.3 MiB/s. Four workers and four outstanding jobs delivered 37.3 MiB/s. Both worker count and admitted concurrency changed. These were short, synthetic Docker Desktop trials, but adding concurrency clearly didn’t help that case.</p>
<hr />
<h2><strong>Waiting for storage is different</strong></h2>
<p>A filesystem worker waiting for storage uses little CPU. Starting another I/O request during that wait can be worthwhile, even if there are more workers than CPUs. Bcrypt spends its time computing, so it can’t offer the same opportunity.</p>
<p>A read served from cache is a different case again: copying the data takes CPU time and memory bandwidth. And sending more requests to storage won’t help once the device is at capacity. In the Node.js PR, the larger pool improved the crypto benchmark but made one filesystem benchmark slower. I wouldn’t choose a default for both from either result alone.</p>
<hr />
<h2><strong>Conclusion</strong></h2>
<p>My objection is to making this automatic. I’d happily increase the pool for an application whose measurements justify it, but I’d test on a busy host and look at slow requests as well as throughput. A nice value doesn’t answer that question for us. And we still have to stop accepting work when the queue’s job or byte budget is full; adding threads can’t make an unbounded queue safe.</p>
]]></content:encoded></item><item><title><![CDATA[State Without a Landlord: Durable Workflows Without a Single Owner]]></title><description><![CDATA[Explore a P2P architecture for durable workflows that makes state portable, verifiable, and independent of a single infrastructure provider.]]></description><link>https://blog.platformatic.dev/state-without-a-landlord-durable-workflows-without-a-single-owner</link><guid isPermaLink="true">https://blog.platformatic.dev/state-without-a-landlord-durable-workflows-without-a-single-owner</guid><category><![CDATA[workflows]]></category><category><![CDATA[sdk]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[p2p]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[Web3]]></category><dc:creator><![CDATA[Luca Maraschi]]></dc:creator><pubDate>Tue, 22 Sep 2026 16:05:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/a40c36da-feb2-450c-b42c-b4937ac7366e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A durable workflow survives crashes, deploys, and <code>sleep("7d")</code>. It can do that because the running process never holds the state. The journal does. Every step's input and output are recorded, and on resume, the orchestrator re-executes from the top and reads each result back from the log instead of running the step again.</p>
<p>This means the journal is the one thing you absolutely cannot lose. Right now, it exists in just one place: a vendor’s managed store, a cloud service, or your own database. Whoever runs that store has the only official copy. The workflow cannot continue without them, and switching providers needs their cooperation.</p>
<p>We call this role a landlord. This is just a technical term. Most operators in this position are capable, trustworthy, and affordable. We are one of them. <a href="https://blog.platformatic.dev/durable-workflows-kubernetes-version-safe">Platformatic World</a> is our self-hosted Kubernetes environment for <a href="https://github.com/vercel/workflow">Workflow SDK</a>, and its journal is managed by a single administrative domain, just like other production Worlds.</p>
<p>Our new paper, <a href="https://arxiv.org/abs/2609.17645">State Without a Landlord</a>, explores what happens if the journal becomes an authenticated, append-only log that is shared among everyone involved in the workflow.</p>
<p>The paper covers two main points:</p>
<ul>
<li><p><strong>An observation:</strong> a durable workflow journal is already, structurally, a peer-to-peer log.</p>
</li>
<li><p><strong>A proposal:</strong> a P2P World for Workflow SDK, where storage, queuing, and authentication resolve to swarm primitives instead of one operator's infrastructure.</p>
</li>
</ul>
<p>One point describes the current reality. The other outlines what could be built on top of it.</p>
<p>This is an architecture proposal, not an implementation. Each claim in the paper is marked as established, proposed, or open, and the last section lists experiments that could disprove it.</p>
<hr />
<h2><strong>Why code portability is not enough</strong></h2>
<p>Vendors of durable execution often claim there is "no lock-in," and at the code level, that’s true: the same workflow can run anywhere. But things are different for workflows that are already running.</p>
<p>For example, imagine a procurement workflow between two companies. Your team gets a vendor quote, and both ACME’s manager and director need to approve it before the order is placed. The approval period lasts 14 days, so the workflow is idle most of the time.</p>
<p>Someone needs to host the workflow, and everyone else must trust that host’s record. This leads to four main issues, listed from least to most serious:</p>
<ul>
<li><p><strong>State lock-in:</strong> Switching providers mid-run means you have to finish every workflow first, which is impossible for long-running or sleeping workflows. If you can only move code but not state, portability only works for new projects.</p>
</li>
<li><p><strong>Availability coupling:</strong> In theory, a workflow could resume anywhere, but in practice, it can only resume where its journal is accessible. So, a system designed to survive failures still relies on a single piece of infrastructure.</p>
</li>
<li><p><strong>Unverifiable history:</strong> The journal is just rows in someone’s database. Anyone with access can change a step’s result, and replaying the workflow will recreate the altered state.</p>
</li>
<li><p><strong>Multi-party runs need a landlord:</strong> For example, ACME’s approval exists only as a row in your database, or your approval exists only in theirs.</p>
</li>
</ul>
<p>Human-run systems can handle this because people work slowly and resolve disputes outside the system. Agent-based systems can’t. When autonomous agents from different organizations run workflows, you can’t assume the parties are known ahead of time, that disputes are rare, or that runs are short. These workflows need state that is shared, independently verifiable, and portable between executors.</p>
<p>This is a peer-to-peer replication problem, and it has already been solved twice by communities working on other problems.</p>
<hr />
<h2><strong>The journal is already a P2P log</strong></h2>
<p>Durable execution relies on three things. The journal is the workflow: together with the code, it fully defines the state. The journal is append-only, with just one writer per run. Replay is deterministic, so anyone with the right code and journal can take over as executor.</p>
<p><a href="https://docs.pears.com/">Hypercore</a>, the log underneath the Pear stack, has the same shape. A core is identified by a public key. Only the holder of the private key can append. Every block is signed and covered by a Merkle tree, so any peer can replicate any subset and verify it without trusting the peer that served it. A writer that rewrites history produces two signed blocks at one sequence number, which is cryptographic proof of its own misbehaviour.</p>
<p>When you compare them, the similarities are structural:</p>
<table style="width:676px"><colgroup><col style="width:260px"></col><col style="width:416px"></col></colgroup><tbody><tr><td><p>Run journal</p></td><td><p>Hypercore</p></td></tr><tr><td><p>Executor identity</p></td><td><p>Core keypair: the append key is the right to advance the run</p></td></tr><tr><td><p>Executor rewrites history</p></td><td><p>Fork proof: silent in a database, evidence in a core</p></td></tr><tr><td><p>Resume after crash</p></td><td><p>Replication plus replay, by any authorized peer</p></td></tr><tr><td><p>Hooks and approvals</p></td><td><p>Autobase over each respondent's own core</p></td></tr><tr><td><p>Large step payloads</p></td><td><p>BitTorrent v2 objects, referenced by infohash</p></td></tr><tr><td><p>"Where is run X?"</p></td><td><p>DHT topic derived from the run key</p></td></tr></tbody></table>

<p>The single-writer rule is crucial. Trying to let multiple masters update workflow state would create a consistency nightmare, which is where many decentralization ideas fail. Durable execution already avoids this. Only one executor advances a run, and everyone else just reads until there’s a clear handoff. Hypercore uses a keypair to enforce the same rule that today’s engines enforce with a lease row in a database.</p>
<p>The same goes for determinism. Autobase needs a deterministic apply function over ordered inputs. Developers who already avoid using <code>"Date.now()"</code> in workflow code have accepted this rule.</p>
<hr />
<h2><strong>Two planes, joined by hashes</strong></h2>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/ae86363c-ec3c-4692-8e1d-e11e50a92ec4.png" alt="" style="display:block;margin:0 auto" />

<p>This architecture separates live coordination from bulk distribution:</p>
<ul>
<li><p><strong>Coordination plane:</strong> Hypercore and Autobase journals. Small, live, signed, totally ordered.</p>
</li>
<li><p><strong>Distribution plane:</strong> BitTorrent v2 swarms. Large, immutable, content-addressed.</p>
</li>
</ul>
<p>A journal shouldn’t include a 2 GB model checkpoint or a container image directly. Instead, it holds a 32-byte infohash, and the actual data moves through infrastructure that’s been tested for decades in tough conditions. Facts point to data by hash, but the data itself doesn’t carry authority.</p>
<p>The workflow bundle and the engine build are pinned the same way. The run manifest names both by infohash, so replaying against the wrong code version becomes structurally impossible instead of operationally avoided. We built <a href="https://blog.platformatic.dev/durable-workflows-kubernetes-version-safe">Platformatic World</a> around that exact hazard on Kubernetes. Content addressing removes it at the data-model level.</p>
<hr />
<h2><strong>Resuming a run you did not start</strong></h2>
<p>If the executor crashes while the procurement run is waiting on ACME, a standby or any participant with the right keys can resume it in five steps:</p>
<ol>
<li><p><strong>Fetch.</strong> Join the DHT topic for the run, replicate the journal from any peer holding it, and verify every block against the Merkle root.</p>
</li>
<li><p><strong>Pin code.</strong> Read the bundle infohash from the manifest, fetch it from the swarm, and verify it by content address.</p>
</li>
<li><p><strong>Authorize.</strong> Succession has one path: an <code>epoch.open</code> record in the run's coordination channel, grounded in a voluntary handoff, a fork proof, or a lapsed liveness challenge, and finalized by the run's indexer majority.</p>
</li>
<li><p><strong>Replay.</strong> Replay the orchestrator against the verified chain and pass two gates before acting.</p>
</li>
<li><p><strong>Advance.</strong> Append new step records to a fresh epoch core. Every replica sees the run resume, and sees who resumed it.</p>
</li>
</ol>
<p>There are two checks in step 4 for a reason. A hash of the state, built from the journal, is a pure function of the journal itself. Any engine reading the same log gets the same hash, so matching hashes don’t tell you anything about the engine. The paper introduces a next-intent record: at each pause, the executor commits to the next call its replay will make, including the call site, call index, and argument hash.</p>
<p>A resumer first checks the transcript hash, which catches differences in schema or decoding. Then it replays and checks its own next intent, which catches engines that agree on history but are about to make a different call. If there’s a mismatch at either step, the resumer stops before making any changes.</p>
<hr />
<h2><strong>Fencing by topology, not by promise</strong></h2>
<p>No capability record in another log can stop a key from signing. If handoff means sharing the run core's secret key, the predecessor keeps it forever. Fork detection is evidence after the fact, not revocation.</p>
<p>So a run isn’t just one Hypercore. It’s a chain of epoch cores, with one single-writer core for each executor’s time in charge. An epoch ends with a closure certificate that commits to the authenticated tree root, not just the length, because a dishonest core could have two signed trees at the same length. After the certificate is finalized, the old key can still add to its own core, but those entries appear after the finalized length. Anyone following the chain sees these as post-close writes by a fenced writer; they’re evidence, not state. This is the classic fencing-token pattern, applied to log structure.</p>
<p>Four invariants carry the safety argument:</p>
<ul>
<li><p><strong>I1. Unique succession.</strong> An epoch has at most one finalized successor.</p>
</li>
<li><p><strong>I2. Unique history.</strong> A finalized epoch prefix identifies exactly one authenticated history.</p>
</li>
<li><p><strong>I3. Durable means survivable.</strong> Every acknowledgment that can survive a failover also survives any allowed epoch transition.</p>
</li>
<li><p><strong>I4. Fence before fire.</strong> No executor starts an external effect until its epoch is the finalized chain head and the effect’s intent record is durable.</p>
</li>
</ul>
<p>Liveness eviction doesn’t assume that silence means failure. An unresponsive executor could be dead, disconnected, or just slow, and no group of witnesses can always tell the difference. Eviction is based on a timeout certificate: a quorum of indexers each confirm, using their own timers, that a challenge wasn’t answered. This allows an epoch to close. It’s not proof of a fault; the goal is to limit any mistaken eviction so it can be fixed and never cause corruption.</p>
<hr />
<h2><strong>Durability is a dial with stated prices</strong></h2>
<p>In a centralized World, durability is confirmed by a database commit behind the scenes. In the P2P World, it’s an explicit policy set for each run:</p>
<p><code>ack: "local" | { replicas: number } | "survivable"</code></p>
<ul>
<li><p><strong>"local"</strong> commits on local append. Hosted-World latency, no protection against executor loss or false eviction.</p>
</li>
<li><p><strong>{ replicas: k }</strong> commits when k replicas hold the block. Crash durability, but the entry can still be orphaned by a legitimate epoch closure.</p>
</li>
<li><p><strong>"survivable"</strong> commits when an acknowledgment certificate from the indexer set is finalized in the coordination view. It is the only level invariant I3 protects, and it costs a coordination-finality round trip. Effect-bearing steps default to it.</p>
</li>
</ul>
<p>The certificate threshold is a = max(ceil((N+1)/2), N - q + 1) for N indexers and finality quorum q. The second term guarantees every certificate intersects every finality quorum. The first guarantees that certificates on two conflicting branches cannot both exist under crash faults.</p>
<p>The P2P World is slower than a local database in microbenchmarks, as expected. But it offers joint custody, verifiability, and executor portability features you can’t get from a local database at any speed. The trade-off is clear and priced per run, not hidden.</p>
<hr />
<h2><strong>What signatures can’t prove</strong></h2>
<p>Signatures and Merkle proofs confirm authorship and order. They never establish truth. A malicious executor can append a valid, non-forking <code>step.end</code> recording an outcome that never happened, and every peer will verify and preserve the lie.</p>
<p>The threat model states which guarantees hold where:</p>
<ul>
<li><p><strong>T1, crash-only.</strong> The design target. No lost or corrupted state given surviving replicas; resume by any authorized keyed peer; divergence detected at resumption seams.</p>
</li>
<li><p><strong>T2, rational or misbehaving participants.</strong> Evidence, not prevention: fork proofs, certificates, audit trails.</p>
</li>
<li><p><strong>T3, Byzantine indexer majorities and network adversaries.</strong> Out of scope, with the degradations stated.</p>
</li>
</ul>
<p>The paper discusses two more limitations in separate sections.</p>
<p>Exactly-once external effects aren’t possible in any World, centralized or not. The process is: record the intent, make it durable, make the call with an idempotency key based on (runId, seq, attempt), and record the outcome. If a successor finds a <code>step.begin</code> without a <code>step.end</code>, it repeats the same call, and an idempotent target gives the same result.</p>
<p>Resuming a run means running its code. Node.js isn’t a sandbox, and neither is Bare. In the procurement flow, if ACME’s standby resumes the run, ACME ends up running your step code on their own infrastructure. The proposed solution is step ownership: no one ever runs another party’s effectful code. Foreign steps are handled like hooks, and the owner’s signed result is used at finality. The orchestrator just replays under the determinism profile, making it the only shared code and the part that can be sandboxed in an isolate or WASM.</p>
<hr />
<h2><strong>Workflow code stays the same. The engine does not.</strong></h2>
<p>The procurement flow is written exactly as it would be against a hosted World:</p>
<pre><code class="language-typescript">"use workflow";
export async function procurement(req: PurchaseRequest) {
 const quote = await fetchVendorQuote(req);                 // "use step"
 const approval = await hook&lt;Approval&gt;("acme-signoff", {
   grantedTo: [ACME.managerKey, ACME.directorKey],          // other org's keys
   quorum: 2,                                               // both must sign
   deadline: "14d",
 });
 if (!approval.granted) return await notifyRejection(req);  // "use step"
 return await placeOrder(quote, approval.receiptRef);       // "use step"
}
</code></pre>
<p>In a hosted World, hook(...) creates a callback URL, and the host’s database records who called it. In the P2P World, it adds a <code>hook.await</code> with ACME’s keys. The approval that lets the run continue is ACME’s own signed entries on their own cores, ordered by Autobase and only acted on at finality. No organization hosts the other’s approval.</p>
<p>"Code unchanged, only a new World" is just a hypothesis, and the paper measures the gap. The real @workflow/world contract covers much more than storage and queues. The architecture also needs features that no World interface currently provides: stable call-site IDs, call-index generation, standard argument hashing, exposing the next suspension intent during replay, and a determinism profile that goes beyond just avoiding <code>Date.now()</code> and <code>Math.random()</code>. These require changes to the compiler and runtime.</p>
<p>The accurate claim is that the workflow source code stays the same. The SDK, compiler output, and execution engine underneath do not.</p>
<hr />
<h2><strong>No flag day: the Mirror World</strong></h2>
<p>No one adopts a new state layer all at once. The adoption path has three phases of shifting custody, not three separate rewrites:</p>
<ol>
<li><p><strong>Mirror.</strong> A World decorator writes every journal entry to the hosted store and to a run core. The hosted store stays authoritative. Participants obtain verifiable replicas and an exit path that does not require the vendor's cooperation.</p>
</li>
<li><p><strong>Custody flip.</strong> Run cores become authoritative, per run or per application. The flip is reversible by mirroring in the opposite direction, because export and import have collapsed into one operation: replication.</p>
</li>
<li><p><strong>Native.</strong> P2P World only. The vendor is one competitor in markets for fungible roles: superpeers, blind replicas, wake services, capability gateways.</p>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/a1ce1af6-bb1e-414b-9377-610068ccc118.png" alt="" style="display:block;margin:0 auto" />

<p>Phase 1 acts as insurance, and insurance comes with costs: extra latency from writing in two places, extra egress and storage for mirrored cores, key distribution before any encrypted data moves, and a job to reconcile any differences from dual writes. The paper lists these costs instead of ignoring them.</p>
<p>The idea behind phase 3 applies to us as much as anyone: centralized infrastructure can speed things up, but it shouldn’t own the state. Speed, wake reliability, observability, and indexes all remain as services on an open platform. What disappears is the position of exclusive control.</p>
<hr />
<h2><strong>What would falsify it?</strong></h2>
<p>A good proposal should list the experiments that could disprove it. Here’s the agenda, ordered by how much each item affects the main claims:</p>
<ul>
<li><p><strong>Minimal prototype.</strong> One run as an epoch chain, one executor, one cold standby. Success means a standby on a different machine, then on a different engine build, resumes a suspended run through the two-gate check with zero manual control, and a deliberately skewed engine is stopped by the intent gate.</p>
</li>
<li><p><strong>Fencing validation.</strong> Implement the epoch chain against real Hypercore semantics and attack it: post-close appends from a fenced predecessor, racing successors, <code>epoch.open</code> under partitioned indexers, closures racing certificate finalization. The deliverable is a safety argument grounded in observed behaviour, or a documented failure that revises the design.</p>
</li>
<li><p><strong>Coordination finality measurement.</strong> Autobase time-to-checkpoint against indexer count and connectivity, and the latency the finality gate adds to approvals and epoch transitions. The design assumes these costs are acceptable. The measurements decide.</p>
</li>
<li><p><strong>World conformance.</strong> Implement the exact versioned @workflow/world contract, run the upstream suite, and publish the results either way.</p>
</li>
</ul>
<p>Problems where even the design isn’t settled are listed as open: step-ownership execution, effect-truth attestation, Byzantine-tolerant coordination, custody-proof hardening, erasure-aware control flow, and network-observer privacy.</p>
<hr />
<h2><strong>What the paper changes</strong></h2>
<p>Durable execution means your workflow survives even if your infrastructure fails. The paper goes further: the run should also survive your provider, your counterparty’s database, and any dispute about whose record is correct.</p>
<p><strong>For workflow authors</strong>, nothing changes in the source code. "use workflow" and "use step" stay the same, and the determinism rules you already follow are what the P2P layer needs.</p>
<p><strong>For operators</strong>, custody becomes a clear policy rather than a side effect of deployment. Durability level, failover set, retention, and liveness tier are all set in a signed manifest, and the mirror phase gives an exit path before any authority changes.</p>
<p><strong>For multi-party and agent systems</strong>, the run’s history is no longer just one party’s database. Approvals are the approver’s own signed entries. Checkpoints are portable receipts for the transcript, not for the whole world. Disputes start with evidence, not arguments over whose logs to trust.</p>
<p><strong>For vendors</strong>, including us, the business shifts from owning state to serving it faster and more reliably than anyone else.</p>
<p>Exclusive storage custody isn’t required for durable execution. The landlord’s storage was never the main support. The prototype tests whether scheduling, fencing, credentials, availability, and finality can be managed through evidence and flexible roles.</p>
<p>You can find the paper at <a href="https://arxiv.org/abs/2609.17645">arxiv.org/abs/2609.17645</a>. Read it, challenge it, and let us know about any failure cases.</p>
]]></content:encoded></item><item><title><![CDATA[Introducing secure-eval-worker]]></title><description><![CDATA[How secure-eval-worker runs untrusted JavaScript in Node.js with least-privilege permissions, host capabilities, worker isolation, & resource limits.]]></description><link>https://blog.platformatic.dev/introducing-secure-eval-worker</link><guid isPermaLink="true">https://blog.platformatic.dev/introducing-secure-eval-worker</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[Security]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Thu, 17 Sep 2026 14:37:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/577fd937-e6a9-4294-b06a-fe7a0d304d99.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Running JavaScript at runtime is becoming more common. Tasks like AI-generated changes, user automation, plugins, and programmable app parts all work better when code runs near the data and APIs it uses.</p>
<p>The main challenge is controlling authority. A regular eval() has the same permissions as its host, and even if you move the code to a worker thread, it still has access to the filesystem, network, environment, and other Node.js features unless you remove them yourself.</p>
<p><a href="https://github.com/platformatic/secure-eval-worker">secure-eval-worker</a> is a new library that lets you run JavaScript scripts, ES modules, and trusted local modules in Node.js workers with only the permissions you choose. It works for both single-use code and longer-running components that talk to their host.</p>
<p>This package uses Node’s Permission Model, clear host capabilities, and limited worker lifetimes. The aim isn’t to create a perfect JavaScript sandbox, but to make least privilege the standard when running code natively in Node.js.</p>
<p><strong>Security boundary:</strong> Node’s Permission Model and worker threads add extra layers of defense, but they don’t fully isolate malicious code. Workers still share the same process, and V8 worker limits don’t cover every possible failure. For risky multi-tenant workloads, use this library inside a separate sandboxed process or container with OS-level limits on CPU, memory, filesystem, network, and syscalls.</p>
<hr />
<h2><strong>Why another way to evaluate JavaScript?</strong></h2>
<p>Node.js already offers several ways to run code dynamically, but they don’t always make it clear what the code is allowed to do.</p>
<p><code>eval()</code> and new <code>Function()</code> run in the current process and inherit all the app’s permissions. A regular worker thread helps manage the code’s lifecycle and keeps heavy tasks off the main event loop, but it still starts with wide access to Node.js features unless you remove them yourself.</p>
<p>For programmable components, you usually want a much tighter set of permissions:</p>
<ul>
<li><p>receive a bounded input;</p>
</li>
<li><p>compute or retain state;</p>
</li>
<li><p>call a few application-defined operations;</p>
</li>
<li><p>return values or emit messages;</p>
</li>
<li><p>stop after a deadline; and</p>
</li>
<li><p>remain unable to turn those operations into general filesystem, network, process, or worker access.</p>
</li>
</ul>
<p><code>secure-eval-worker</code> is designed for this kind of contract. Guest code only gets the data and specific capabilities you give it, instead of inheriting all the app’s permissions.</p>
<hr />
<h2><strong>A quick look at the API</strong></h2>
<p>The simplest API is runUntrustedCode(). It starts a new worker, runs the code as an async function, returns the result, and then shuts down the worker:</p>
<p>import { runUntrustedCode } from 'secure-eval-worker'</p>
<pre><code class="language-javascript">import { runUntrustedCode } from 'secure-eval-worker'
const total = await runUntrustedCode('return input.values.reduce((sum, value) =&gt; sum + value, 0)', {
 input: { values: [10, 20, 12] },
 timeoutMs: 500,
 environment: { LANG: 'C' }
})

console.log(total) // 42
</code></pre>
<p>The guest code gets a single argument called <code>input</code>. Data sent in and out is copied by value, not by reference, so shared memory isn’t allowed. The worker also gets a specific environment instead of inheriting <code>process.env</code>.</p>
<p>Each time you call it, a new worker is created.</p>
<hr />
<h2><strong>Persistent components, not just single-use functions</strong></h2>
<p>Some tasks need to keep state and handle ongoing messages, not just return one result. <code>createUntrustedWorker()</code> lets you make a persistent component with a set lifetime and handles messages one at a time:</p>
<pre><code class="language-javascript">import { createUntrustedWorker } from 'secure-eval-worker'

const counter = createUntrustedWorker(
 `
 let value = input.initialValue

 send({ status: 'ready', value })

 onMessage((message) =&gt; {
   if (message.type === 'increment') {
     value += message.amount
   }

   return { value }
 })
`,
 {
   input: { initialValue: 40 },
   startupTimeoutMs: 1000,
   messageTimeoutMs: 500,
   lifetimeTimeoutMs: 60_000
 }
)

counter.on('message', message =&gt; {
 console.log('component message:', message)
})

await counter.ready
console.log(await counter.request({ type: 'increment', amount: 2 }))
// { value: 42 }

await counter.terminate()
</code></pre>
<p>Script components get <code>input</code>, <code>send()</code>, and <code>onMessage()</code>. You can also use self-contained ES modules, as long as the module exports a setup function that takes these operations. This keeps normal JavaScript features like lexical state, timers, async functions, and built-in modules, as long as they fit within the worker’s limited permissions.</p>
<p>Each request has a deadline that includes cloning, queuing, and handling. If the deadline passes, the whole session ends, since you can’t safely interrupt CPU-heavy JavaScript in a worker without risking its state.</p>
<hr />
<h2><strong>Authority is provided through host functions</strong></h2>
<p>Useful code often needs to do more than just calculations. It might need to fetch a record, check a feature flag, log an event, or call an app service. If you give it a general database or network client, you’re giving back the broad permissions you wanted to avoid.</p>
<p>Host functions offer a more limited and controlled way to give authority:</p>
<pre><code class="language-javascript">const result = await runUntrustedCode('return records.find(input.id)', {
 input: { id: 'record-42' },
 hostFunctions: {
   records: {
     find: async id =&gt; database.records.find(id)
   }
 }
})
</code></pre>
<p>The guest sees <code>records.find()</code> as a promise-returning function. The host retains control over the implementation, credentials, authorization, validation, and output. Namespaces and functions are installed as read-only globals, and malformed or accessor-based capability definitions are rejected before the worker starts.</p>
<p>This is capability-oriented design: expose <code>records.find(id)</code>, <code>not fetch(url)</code>; expose <code>audit.record(event)</code>, not unrestricted database access.</p>
<p>Host functions still grant authority, so their code must check every argument from the guest and make sure the right tenant or user is used in trusted closures. Session and request IDs help with tracing, but they aren’t used for authorization. Also, writes should be idempotent at the app level, since canceling a request can’t undo a side effect that’s already happened.</p>
<p>For host operations that can be canceled, <code>getHostFunctionContext()</code> gives you an <code>AbortSignal</code> that triggers if the session is canceled, times out, fails, or ends. Any unexpected host errors are hidden before reaching the guest. Applications should only throw <code>HostFunctionError</code> when it’s safe to share a specific message and code.</p>
<hr />
<h2><strong>What happens before guest code runs</strong></h2>
<p>The key security rule is simple: remove all extra permissions before compiling, importing, or running any code provided by the caller.</p>
<p>A source-string execution follows this sequence:</p>
<ol>
<li><p><strong>Acquire admission.</strong> The process reserves a worker slot before inspecting caller-controlled options or cloning input.</p>
</li>
<li><p><strong>Validate the boundary.</strong> Source size, options, environment, resource limits, host functions, and protocol values are checked against explicit allowlists and limits.</p>
</li>
<li><p><strong>Construct a restricted worker.</strong> The worker starts with Node’s Permission Model enabled, only the worker permission, an explicit environment, and V8 resource limits.</p>
</li>
<li><p><strong>Drop nested-worker authority.</strong> The trusted bootstrap captures the primitives it needs and immediately calls <code>process.permission.drop('worker')</code>.</p>
</li>
<li><p><strong>Close ambient communication.</strong> It creates private channels, closes and hides <code>parentPort</code>, and removes access to inherited worker environment data.</p>
</li>
<li><p><strong>Harden known same-process surfaces.</strong> Filesystem, network, process mutation, loader hooks, native bindings, cross-thread messaging, runtime inspection, and other reviewed escape surfaces are disabled before guest execution.</p>
</li>
<li><p><strong>Compile and run the guest.</strong> Only after the permission drop and hardening does the bootstrap compile a script or import a self-contained module.</p>
</li>
</ol>
<p>The order is important. If you validate code after it starts, or drop permissions after importing a module, there’s a window where the code has more authority than you want.</p>
<p>The security hardening is tied to specific Node.js versions. The first release works with Node.js 26.3.0 through the current 26.x, since it needs <code>process.permission.drop()</code>. Future major Node.js versions will need a new review, since new features or APIs could change what’s accessible.</p>
<hr />
<h2><strong>A protocol designed for an untrusted participant</strong></h2>
<p>A worker boundary also separates data and control. Guest code shouldn’t be able to sneak in shared authority, fake lifecycle messages, replay old responses, or use up memory by sending unlimited output.</p>
<p><code>secure-eval-worker</code> creates a private <code>MessageChannel</code> inside the trusted bootstrap and authenticates messages with a per-session HMAC and monotonic sequence number. Authentication covers the exact V8-serialized bytes, not a second reconstruction of the value. Capturing or replaying a message cannot produce a valid new control operation.</p>
<p>Values are intentionally narrower than everything Node’s structured clone can carry. Supported values include primitives, plain objects and arrays, <code>ArrayBuffer</code> and non-shared views, <code>Date</code>, <code>RegExp</code>, <code>Map</code>, and <code>Set</code>. The boundary rejects:</p>
<ul>
<li><p><code>SharedArrayBuffer</code> and other shared-memory representations;</p>
</li>
<li><p>custom class instances and authority-bearing platform objects;</p>
</li>
<li><p>accessors, symbols, and non-enumerable properties on data objects;</p>
</li>
<li><p>ports, file handles, sockets, and cryptographic key objects; and</p>
</li>
<li><p>ordinary <code>Error</code> values, whose native serialization can disclose unwanted implementation details.</p>
</li>
</ul>
<p>If guest code throws an error, it becomes an <code>UntrustedCodeError</code> on the host. The remote stack trace can be kept as limited diagnostic text, but since it comes from the guest, it shouldn’t be trusted as proof of what happened.</p>
<p>By default, console output from guest code is ignored and not sent to app logs. Diagnostics are optional and use a separate secure channel with limits on record size and total bytes. Formatting avoids reading object properties or running custom inspection, and any terminal control characters are escaped.</p>
<hr />
<h2><strong>Local modules without granting the source tree</strong></h2>
<p>Self-contained source strings provide the narrowest filesystem policy: no filesystem permission remains when guest execution begins. They work well for generated code or module graphs bundled by a trusted host.</p>
<p>Existing components may need Node’s native ESM loader, relative imports, dynamic imports, or package resolution. For those cases, <code>runUntrustedFile()</code> and <code>createUntrustedWorkerFromFile()</code> accept an entry file and a trusted root:</p>
<pre><code class="language-javascript">import { runUntrustedFile } from 'secure-eval-worker'

const result = await runUntrustedFile('./components/calculate.mjs', {
 rootDirectory: './components',
 input: { values: [10, 20, 12] },
 timeoutMs: 500
})
</code></pre>
<p>Before starting the worker, the host copies the allowed files into a private temporary folder. It skips symbolic links and special files, checks that files are really inside the allowed folder, and enforces limits on the number and size of files. The worker can only read from this snapshot, not from the original source path.</p>
<p>This setup stops later changes to the source tree from redirecting imports outside the copied files. The guest can use Node’s loader and a limited synchronous <code>node:fs</code> read inside the snapshot. It can’t write files, use promise-based filesystem APIs, read outside the snapshot, inherit file descriptors, create nested workers, or use native addons.</p>
<p><code>rootDirectory</code> gives the guest access to all copied files, so don’t include secrets or unrelated files in that folder. The source tree and anything that can change it must be trusted during setup, and the temporary folder and any process with the same identity must be trusted while the snapshot exists. Node.js APIs can’t always guarantee files stay contained if directories are renamed or processes race, and the copy isn’t a true atomic snapshot. If these risks matter, use an immutable app-owned tree and an OS sandbox with a separate identity.</p>
<hr />
<h2><strong>Bound the entire lifecycle, not just execution time</strong></h2>
<p>A timeout by itself isn’t enough to control resources. This package sets limits at several stages:</p>
<table style="width:691px"><colgroup><col style="width:327px"></col><col style="width:364px"></col></colgroup><tbody><tr><td><p>Boundary</p></td><td><p>Default behavior</p></td></tr><tr><td><p>Concurrent admitted workers</p></td><td><p>4, fail-fast with no internal queue</p></td></tr><tr><td><p>Source size</p></td><td><p>64 KiB</p></td></tr><tr><td><p>Setup input</p></td><td><p>1 MiB serialized</p></td></tr><tr><td><p>Protocol message</p></td><td><p>1 MiB serialized</p></td></tr><tr><td><p>Unsolicited messages and attempted host calls</p></td><td><p>1,024 messages and 16 MiB cumulatively</p></td></tr><tr><td><p>Host-function calls</p></td><td><p>256 total and 32 in flight</p></td></tr><tr><td><p>Persistent startup</p></td><td><p>1 second</p></td></tr><tr><td><p>Persistent request</p></td><td><p>1 second</p></td></tr><tr><td><p>Persistent lifetime</p></td><td><p>30 seconds</p></td></tr></tbody></table>

<p>The one-shot <code>timeoutMs</code> covers input cloning, startup, and execution. For local files, it also covers staging. If cloning or native work can’t be stopped in the middle, any timeout is reported right after, and the worker might take extra time to fully exit.</p>
<p>Admission remains occupied until the worker actually exits, even if the public termination deadline has already produced an error. This prevents slow termination from allowing the process to exceed its configured worker limit. Sandbox workers must be created from the process main thread; creation from a host worker thread fails closed. Local workers also have descriptor caps of 64 per worker and 256 process-wide, independent of worker admission.</p>
<p>The default worker limit is set low on purpose. On Linux x86-64, each worker added about 12–20 MiB of memory in tests with Node.js 26. This isn’t a universal rule or a performance benchmark. You should measure your own app’s needs before changing the limit.</p>
<p>V8 resource limits and admission control can’t cover every possible memory or CPU issue, like ArrayBuffers, WebAssembly, native code, or host functions. That’s another reason to use process or container isolation for risky workloads.</p>
<hr />
<h2><strong>Why one-shot workers are not pooled</strong></h2>
<p>Starting a worker takes resources, so pooling might seem like a good idea. The problem is making sure a used Node.js environment is really clean and safe for new untrusted code.</p>
<p>A previous guest could change global objects, fill module caches, add listeners or timers, leave unfinished tasks, or keep data in closures. Permissions, environment, resource limits, secrets, counters, and output limits are all set up for each worker when it’s created.</p>
<p>Trying to clean up after each use isn’t the same as having a true reset. Until Node.js offers a fully disposable environment with the same permission controls, <code>secure-eval-worker</code> creates a new worker for every one-shot call. Persistent workers are created on purpose, so you control their state and how long they live.</p>
<hr />
<h2><strong>Testing the security boundary</strong></h2>
<p>The repository tests the same exploit matrix across one-shot scripts, persistent scripts, source modules, one-shot files, and persistent file modules. The suite covers permission denial, inherited descriptors, process and V8 surfaces, cross-thread APIs, shared memory, protocol limits, host-function failures, lifecycle races, local-root containment, and cleanup behavior. CI runs on Ubuntu, macOS, and Windows across the supported Node.js 26 range.</p>
<p>These tests show regression evidence, not a guarantee or security certification. Runtime protections need to keep up with Node.js changes, and any claims about deployment only apply to the versions and platforms that have been reviewed and tested.</p>
<hr />
<h2><strong>Getting started</strong></h2>
<p>You can find the source code, API docs, threat model notes, and test suite in the <a href="https://github.com/platformatic/secure-eval-worker">platformatic/secure-eval-worker</a> repository. Right now, the project is only available from source and hasn’t been published to npm yet. You can install the current version directly from GitHub:</p>
<pre><code class="language-plaintext">npm install secure-eval-worker
</code></pre>
<p>The package currently works with Node.js 26.3.0 through the latest 26.x release. Start by using a one-shot source string without host functions, and only add the minimum capabilities your component needs. If you use local modules, set up a dedicated, unchangeable root folder. Set admission limits based on your workload, not by allowing unlimited concurrency.</p>
<hr />
<h2><strong>Final thoughts</strong></h2>
<p><code>secure-eval-worker</code> changes dynamic JavaScript execution from a broad-permission task to an explicit contract: you send in limited data, grant only specific capabilities, get back authenticated messages, and keep control of the lifecycle on the host side.</p>
<p>Its most important design choices are also the most straightforward:</p>
<ul>
<li><p>permissions are removed before guest code runs;</p>
</li>
<li><p>capabilities are explicit and application-defined;</p>
</li>
<li><p>protocol values and output are bounded;</p>
</li>
<li><p>capacity is reserved before attacker-controlled work;</p>
</li>
<li><p>slots are retained until resources really exit; and</p>
</li>
<li><p>fresh one-shot workers are preferred over an unverifiable reset.</p>
</li>
</ul>
<p>If your app needs generated transformations, programmable workflows, or stateful JavaScript components, <a href="https://github.com/platformatic/secure-eval-worker">secure-eval-worker</a> gives you a practical way to use least privilege. Use it as one part of your security setup, keep permissions as limited as possible, and add process or container isolation when needed.</p>
]]></content:encoded></item><item><title><![CDATA[Introducing @platformatic/memcached]]></title><description><![CDATA[Platformatic's high-performance memcached client for Node.js, with zero dependencies, request pipelining, and over 350,000 SETs per second.]]></description><link>https://blog.platformatic.dev/introducing-platformatic-memcached</link><guid isPermaLink="true">https://blog.platformatic.dev/introducing-platformatic-memcached</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Developer]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[performance]]></category><category><![CDATA[caching]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[memcached]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Tue, 15 Sep 2026 14:27:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/13565708-60b0-445c-8864-6893cc4a8542.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://memcached.org/">memcached</a> has been a reliable cache for more than twenty years and still competes with newer options. It’s a simple, in-memory key/value store with very low latency, no background threads, and just one binary to deploy. However, most Node.js clients for memcached are outdated. Many were built before the current protocol, are no longer maintained, and don’t make the most of memcached’s performance.</p>
<p>We’ve been running memcached at Platformatic and noticed the clients we relied on were the slowest link. So we built our own: <a href="https://github.com/platformatic/memcached">@platformatic/memcached</a>, a minimal, high-performance client for Node.js built on the <strong>meta text protocol</strong>, with zero runtime dependencies and full request pipelining. In our benchmarks, it does over 350,000 SETs and 369,000 GETs per second on a single connection; roughly 3x faster than the fastest client we compared it against.</p>
<hr />
<h2><strong>Why the meta protocol</strong></h2>
<p>memcached ships three wire protocols, and most Node.js clients use the wrong one.</p>
<p>Most older clients use the classic text protocol, which is wordy and requires parsing each response line by line. Its responses can be unclear: <code>NOT_FOUND</code>, <code>ERROR</code>, and <code>CLIENT_ERROR</code> are only identified by matching strings, so a typo or new error message can cause your client to lose sync without warning. The binary protocol is now **deprecated and isn’**t recommended for new projects.</p>
<p>The meta protocol, added in memcached 1.6, was made to replace both older protocols. It uses compact, single-line commands and responses, clear flags, and length-prefixed data blocks, so values with <code>\r\n</code> are handled safely. Every command, even delete, supports CAS, and the server returns opaque tokens so the client can match responses correctly. This is the recommended protocol, and our client uses it exclusively, supporting the meta commands <code>mg</code>, <code>ms</code>, <code>md</code>, <code>ma</code>, <code>mn</code>, as well as <code>version</code> and <code>stats</code> for health checks and observability.</p>
<pre><code class="language-javascript">import { Client } from '@platformatic/memcached'

const client = new Client('localhost:11211')

await client.set('greeting', 'hello', { ttl: 60 })
const value = await client.get('greeting')
console.log(value.toString()) // 'hello'

await client.close()
</code></pre>
<hr />
<h2><strong>The same design that made @platformatic/kafka fast</strong></h2>
<p>We’ve done this before with <a href="https://github.com/platformatic/kafka">@platformatic/kafka</a>, which uses the same performance strategies for Kafka. That includes full request pipelining on a single connection, incremental buffer-based parsing, and combining socket writes into <code>writev</code> calls. Our memcached client uses the same approach.</p>
<p><strong>Full request pipelining:</strong> memcached handles commands in order on each connection, so responses are matched using a FIFO queue of pending operations. There’s no need for per-request locking. You can send commands at the same time (for example, with <code>Promise.all</code>), and they’ll share socket writes and network trips.</p>
<pre><code class="language-javascript">import { Client } from '@platformatic/memcached'

const client = new Client('localhost:11211')

await client.set('greeting', 'hello', { ttl: 60 })
const value = await client.get('greeting')
console.log(value.toString()) // 'hello'

await client.close()
</code></pre>
<p>There’s no need for an extra batching layer here.</p>
<p><strong>Opaque-token verification:</strong> Each command includes an opaque token (<code>O</code> flag) that the server sends back. The client checks this token on every response, so if the protocol gets out of sync, it’s caught right away instead of returning incorrect data. This is what separates a fast client from one that’s fast but sometimes wrong.</p>
<p><strong>Incremental, Buffer-based parsing:</strong> Partial frames are handled across TCP chunks, and value bytes are read by length, not by scanning. If a value contains <code>\r\n</code> (the protocol’s frame delimiter), it’s still safe because the client doesn’t look for it inside the value.</p>
<p><strong>Coalesced socket writes:</strong> Commands sent in the same synchronous block are grouped and sent together as a single <code>writev</code> system call. The <code>autoPipelining</code> option lets you control when flushing happens. The default, 'microtask', flushes at the next microtask checkpoint for low latency on light traffic. The 'tick' option flushes at the end of the event loop, like ioredis, so many concurrent handlers can combine their gets into one system call.</p>
<p><strong>Zero runtime dependencies:</strong> The client only uses <code>node:net</code>. There are no extra dependencies to audit, no supply-chain risks, and no version conflicts.</p>
<p>The source code is written in a subset of TypeScript that can be erased, and it runs directly on Node.js after type stripping during development. The published package includes plain JavaScript and declaration files, so you just need Node.js version 22.12.0 or newer to use it.</p>
<hr />
<h2><strong>The API</strong></h2>
<p>The client is intentionally simple, but it includes everything you need for a production cache:</p>
<ul>
<li><p><code>get / gets</code>: read a value, or read it with its CAS token for optimistic concurrency</p>
</li>
<li><p><code>set, add, cas</code>: unconditional store, set-if-not-exists, and compare-and-swap, returning <code>false</code> on conflict instead of throwing</p>
</li>
<li><p><code>delete</code>: optionally CAS-guarded, so the classic lock pattern is safe</p>
</li>
<li><p><code>incr / decr</code>: atomic counters, returning the new value as a <code>bigint</code></p>
</li>
<li><p><code>noop</code>, <code>version</code>, <code>stats</code>: health checks and observability, with a fleet-wide <code>statsAll()</code> that never rejects on a single node failure</p>
</li>
</ul>
<p>Here’s the lock pattern, using set-if-not-exists plus a token-checked unlock:</p>
<pre><code class="language-javascript">const acquired = await client.add('lock:job', 'my-token', { ttl: 30 })
if (acquired) {
 try {
   // ... critical section ...
 } finally {
   const current = await client.gets('lock:job')
   if (current?.value.toString() === 'my-token') {
     await client.delete('lock:job', { cas: current.cas })
   }
 }
}
</code></pre>
<p>Values are <code>Buffers</code> in and out; no implicit serialization, so you decide what goes in. Keys are printable ASCII without whitespace, at most 250 bytes.</p>
<hr />
<h2><strong>Performance</strong></h2>
<p>Here’s SET/GET throughput against the notable Node.js memcached clients, each running with its best-known configuration. This client and memjs pipeline on a single connection; memcache-client and the 3rd-Eden memcached client get a 10-connection pool because they don’t pipeline the same way. Median of 3 runs, 50,000 operations at concurrency 500 against <code>memcached:alpine</code> on loopback, Node.js 24.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/8c7e4bfa-4c01-4f81-aac3-556cd83d0009.png" alt="" style="display:block;margin:0 auto" />

<p>The exact numbers will vary depending on your machine, and you can reproduce them using node <code>packages/memcached/benchmarks/compare-all.js</code>. The main takeaway is that pipelining a single connection outperforms using a pool of ten connections. Older clients try to solve this with more hardware, but a better parser fixes it without extra cost.</p>
<hr />
<h2><strong>Production features</strong></h2>
<p>The real test for a cache client is how it performs in real-world situations, so we made sure this one covers all the important features.</p>
<p><strong>Client-side sharding:</strong> memcached doesn’t have a server-side clustering protocol, so each node is independent and sharding happens on the client. You can pass an array of addresses, and keys are routed using ketama-style consistent hashing (160 points per node on a 32-bit md5 ring). This way, adding or removing a node only remaps about 1/N of the keyspace. Routing stays the same across processes and restarts. If a node goes down, commands for its keys are rejected while it reconnects, but other nodes keep working. Keys aren’t rehashed to other nodes, which avoids stale reads when the node returns.</p>
<p><strong>ElastiCache auto discovery: With a static server list, you need to update the</strong> config and restart every process when the cluster grows. AWS ElastiCache provides a configuration endpoint that clients can poll for the current node list. You can use this as the server address, and the client will set up the ring from the first response, re-poll at intervals, and only apply newer topology versions. This way, a stale or repeated response can’t roll the cluster back. If the endpoint can’t be reached, the last known topology stays in place and polling continues.</p>
<p><strong>TLS and authentication:</strong> Both <code>memcacheds://</code> URLs and explicit <code>node:tls</code> options are supported, including per-certificate configuration. memcached’s ASCII authfile mode also works (<code>memcached -Y /path/to/authfile</code>), with credentials in options or the URL. The client authenticates as the first command on every connection, including automatic reconnections, before any queued command is sent. SASL is not supported, since it uses the deprecated binary protocol.</p>
<p><strong>Connection pooling:</strong> The memcached protocol doesn’t support multiplexing, so responses always come back in the order they were requested. This means a pipelined connection can get blocked if one large value is being transferred, while smaller gets wait behind it. By setting <code>poolSize</code>, each command goes to the pool member with the fewest outstanding requests, so small operations can move around a busy connection. Pooling works with sharding, giving you <code>poolSize</code> connections per node, with keys still routed to nodes first.</p>
<p><strong>Reconnection with exponential backoff:</strong> The constructor connects right away in the background. Commands sent before the connection is ready are queued and sent once connected. If there’s a socket error, in-flight commands are rejected with <code>ConnectionError</code>, since memcached may have partially processed them and automatic retry could be unsafe. The client reconnects automatically with exponential backoff. The <code>close() method</code> waits for in-flight commands to finish, then closes everything safely.</p>
<hr />
<h2><strong>Observability built in</strong></h2>
<p>Every client provides metrics and diagnostics through two exporter-agnostic interfaces that have almost no overhead when not used.</p>
<p><code>client.metrics()</code> returns a plain object with counters and gauges, such as commands issued, completed, or failed per wire verb, pending pipeline depth, socket writes and flushes, reconnects, and bytes read or written. This is a stable API, and a Prometheus setup can scrape it using a <code>collect()</code> callback.</p>
<p>Per-operation events are published on <a href="https://nodejs.org/api/diagnostics_channel.html">node:diagnostics_channel</a>, so subscribers only pay when they subscribe. If there are no subscribers, the client skips all payload allocation. The companion package, <a href="https://github.com/platformatic/memcached/tree/main/packages/memcached-otel">@platformatic/memcached-otel</a>, listens to these events and turns each command into a single <code>CLIENT</code> span using OpenTelemetry database conventions. There’s no need for module patching or monkey-patching, and it traces every client in the process, even those created before it was enabled.</p>
<pre><code class="language-javascript">import { MemcachedInstrumentation } from '@platformatic/memcached-otel'
import { registerInstrumentations } from '@opentelemetry/instrumentation'

registerInstrumentations({
 instrumentations: [new MemcachedInstrumentation()]
})
</code></pre>
<p>Keys can contain sensitive data, so diagnostics never include values. Keys are only included if the client is created with <code>diagnosticsIncludeKeys:true</code>.</p>
<hr />
<h2><strong>Why we needed it</strong></h2>
<p>This client isn't a hobby. It backs the memcached storage adapter for <a href="https://blog.platformatic.dev/gateway-request-deduplication-nodejs">Platformatic Gateway request deduplication</a>, the feature we announced recently for collapsing concurrent duplicate reads before a burst reaches your application. Gateway deduplication coordinates in-flight requests with short-lived locks and response buffers, and memcached is the storage engine for that coordination when you want it distributed across replicas. We needed a client that could sustain that traffic without becoming the bottleneck, and none of the existing ones could.</p>
<hr />
<h2><strong>An honest status</strong></h2>
<p><code>@platformatic/memcached</code> is currently <strong>private and experimental</strong>. It powers the gateway’s memcached adapter, and the API may change before it’s released publicly. This is intentional—we want to make sure it’s stable with real workloads before finalizing it. The client is fully tested against real memcached servers using Docker, including auth, TLS, interop, and the compiled package. The engineering is production-grade; it’s just the API that’s still being refined.</p>
<hr />
<h2><strong>Try it</strong></h2>
<p>If you use memcached and want a faster client, or if you’re building on the meta protocol and need a reference implementation, give this a try:</p>
<pre><code class="language-plaintext">npm install @platformatic/memcached
</code></pre>
<p>You can find the code on GitHub at <a href="https://github.com/platformatic/memcached">platformatic/memcached,</a> including both the client and the OpenTelemetry instrumentation. Benchmark scripts are included, so you can test the numbers on your own hardware.</p>
<p>A fast, correct cache client matters because caches sit on the hot path of almost everything you serve. Pipelining one connection instead of pooling ten, parsing by length instead of scanning, and verifying responses with opaque tokens.</p>
<p>That’s the difference between a client that’s merely fast and one you can trust at 350,000 operations per second. If you hit an edge case or a rough spot, <a href="https://github.com/platformatic/memcached/issues">open an issue</a>; real workloads are exactly what will shake out the remaining ones.</p>
]]></content:encoded></item><item><title><![CDATA[Query Pipelining in node-postgres: 2-3x Throughput With One Line of Code]]></title><description><![CDATA[Learn how query pipelining in node-postgres cuts latency and delivers up to 2.4x higher throughput with one configuration change.]]></description><link>https://blog.platformatic.dev/query-pipelining-in-node-postgres-2-3x-throughput-with-one-line-of-code</link><guid isPermaLink="true">https://blog.platformatic.dev/query-pipelining-in-node-postgres-2-3x-throughput-with-one-line-of-code</guid><category><![CDATA[Node.js]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[postgres]]></category><category><![CDATA[Query]]></category><category><![CDATA[performance]]></category><category><![CDATA[database]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Pipeline]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Tue, 18 Aug 2026 14:45:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/865934ca-26ac-4b36-a7fb-370a28711d31.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Each time you send a query to PostgreSQL, there’s a delay while your client waits for a response before sending the next one. This is fine for one query, but if you send ten, you wait ten times when you could have waited just once.</p>
<p>PostgreSQL has allowed pipelining since version 7.4, released in 2003. With pipelining, a client can send several queries in a row without waiting for each response, and the server handles them in order. Each query still gets its own result and error handling, so you don’t have to wait between them.</p>
<p>PostgreSQL 14, released in September 2021, added a pipeline API to libpq with functions like <code>PQenterPipelineMode()</code>, <code>PQpipelineSync()</code>, <code>PQexitPipelineMode()</code>, and <code>PQpipelineStatus()</code>. Craig Ringer and Alvaro Herrera developed this feature. The release notes say it lets applications send several queries at once, which reduces latency. You can find full details in the libpq pipeline mode documentation.</p>
<p>Pipelining has always been possible at the protocol level, even before libpq or PostgreSQL 14. Any client that talks directly to the wire protocol can send several queries before reading the responses. node-postgres does this by implementing the PostgreSQL wire protocol in JavaScript, so it can pipeline with any PostgreSQL version from 7.4 onward. The native client (<code>pg-native</code>), which uses libpq, requires PostgreSQL 14 or newer client libraries.</p>
<p>Until now, node-postgres didn’t use this feature.</p>
<p>Opt-in query pipelining shipped in <code>pg 8.23.0</code> and <code>pg-native 3.9.0</code>, released on August 8, 2026 via <a href="https://github.com/brianc/node-postgres/pull/3652">PR #3652</a>. It’s documented at <a href="http://node-postgres.com/features/pipelining">node-postgres.com/features/pipelining</a>.</p>
<pre><code class="language-plaintext">npm install pg@^8.23.0
</code></pre>
<hr />
<h2>What it looks like</h2>
<pre><code class="language-javascript">const { Client } = require('pg')

const client = new Client({ pipeline: true })
await client.connect()

const [users, orders, inventory] = await Promise.all([
 client.query('SELECT * FROM users WHERE id = $1', [userId]),
 client.query('SELECT * FROM orders WHERE user_id = $1', [userId]),
 client.query('SELECT * FROM inventory WHERE warehouse_id = $1', [warehouseId])
])

await client.end()
</code></pre>
<p>You only need to set one option, and there’s no new API to learn. All query types work, including plain text, parameterized, and named prepared statements. Queries are sent to the server right away, and responses come back in order.</p>
<hr />
<h2>How it works internally</h2>
<p>Without pipelining, node-postgres keeps a queue of queries and handles them one by one. The client sends a query, waits for a ReadyForQuery message, and then sends the next.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/8fb15316-4c74-491e-8a2c-327fe224bead.png" alt="" style="display:block;margin:0 auto" />

<p>When pipelining is turned on, the client manages queries using three queues:</p>
<ol>
<li><p><code>_queryQueue</code> – queries waiting to be sent</p>
</li>
<li><p><code>_sentQueryQueue</code> – queries on the wire, waiting for responses</p>
</li>
<li><p><code>_activeQuery</code> – the query whose response is currently being processed</p>
</li>
</ol>
<p>When you call <code>client.query()</code>, the query goes into _<code>queryQueue</code><em>.</em> On the next event loop tick, <code>_pulsePipelinedQueryQueue()</code> drains the entire queue onto the wire, moving each query to <code>_sentQueryQueue</code>. As <code>_ReadyForQuery</code> messages arrive from the server, the next query is promoted from <code>_sentQueryQueue</code> to <code>_activeQuery</code>, and its response is delivered.</p>
<p>Each query sends a full <code>Parse/Bind/Describe/Execute/Sync</code> sequence. The Sync message is what gives each query its own error boundary in PostgreSQL’s protocol. A failing query in the middle of a batch does not affect the others:</p>
<pre><code class="language-javascript">const results = await Promise.allSettled([
 client.query('SELECT 1 AS num'),
 client.query('SELECT INVALID SYNTAX'),
 client.query('SELECT 3 AS num')
])

console.log(results[0].status) // 'fulfilled'
console.log(results[1].status) // 'rejected'
console.log(results[2].status) // 'fulfilled'
</code></pre>
<hr />
<h2><strong>Benchmarks</strong></h2>
<p>All numbers are from a single client running against a local PostgreSQL instance. The pipelined benchmarks use batches of 10 concurrent queries dispatched with <code>Promise.all</code>.</p>
<h3><strong>JS client (</strong><code>pg</code><strong>)</strong></h3>
<table style="min-width:474px"><colgroup><col style="min-width:25px"></col><col style="width:149px"></col><col style="width:150px"></col><col style="width:150px"></col></colgroup><tbody><tr><td><p>Query type</p></td><td><p>Serial (qps)</p></td><td><p>Pipelined (qps)</p></td><td><p>Speedup</p></td></tr><tr><td><p>Simple <code>SELECT 1</code></p></td><td><p>10,746</p></td><td><p>25,294</p></td><td><p><strong>2.35x</strong></p></td></tr><tr><td><p>Parameterized</p></td><td><p>9,516</p></td><td><p>14,226</p></td><td><p><strong>1.50x</strong></p></td></tr><tr><td><p>Named prepared</p></td><td><p>9,983</p></td><td><p>22,160</p></td><td><p><strong>2.22x</strong></p></td></tr></tbody></table>

<h3><strong>Native client (</strong><code>pg-native</code><strong>)</strong></h3>
<table style="min-width:474px"><colgroup><col style="min-width:25px"></col><col style="width:149px"></col><col style="width:150px"></col><col style="width:150px"></col></colgroup><tbody><tr><td><p>Query type</p></td><td><p>Serial (qps)</p></td><td><p>Pipelined (qps)</p></td><td><p>Speedup</p></td></tr><tr><td><p>Simple <code>SELECT 1</code></p></td><td><p>9,446</p></td><td><p>21,524</p></td><td><p><strong>2.28x</strong></p></td></tr><tr><td><p>Parameterized</p></td><td><p>8,670</p></td><td><p>20,792</p></td><td><p><strong>2.40x</strong></p></td></tr></tbody></table>

<h3><strong>JS vs native comparison</strong></h3>
<table style="min-width:428px"><colgroup><col style="min-width:25px"></col><col style="width:180px"></col><col style="width:223px"></col></colgroup><tbody><tr><td><p>Query type</p></td><td><p>JS pipelined (qps)</p></td><td><p>Native pipelined (qps)</p></td></tr><tr><td><p>Simple <code>SELECT 1</code></p></td><td><p>25,294</p></td><td><p>21,524</p></td></tr><tr><td><p>Parameterized</p></td><td><p>14,226</p></td><td><p>20,792</p></td></tr></tbody></table>

<p>The JS client is faster for simple queries because crossing from JavaScript to C++ for each query adds more overhead than native parsing saves. For parameterized queries, the native client is faster because libpq’s pipeline mode batches queries in C and avoids crossing the boundary for each one.</p>
<p>These results are from a local machine. On a real network with latency, pipelining gives an even bigger speed boost because it cuts down on idle time that grows with round-trip time. For example, if each round-trip takes 1ms, running 10 queries in serial means 10ms of waiting, but pipelining removes that delay.</p>
<hr />
<h2>Named prepared statements</h2>
<p>Named prepared statements work with pipelining. When two pipelined queries use the same statement name, node-postgres tracks which Parse messages have been submitted (but not yet confirmed) and avoids sending duplicate Parse requests:</p>
<pre><code class="language-javascript">const queries = Array.from({ length: 100 }, (_, i) =&gt; ({
 name: 'get-user',
 text: 'SELECT * FROM users WHERE id = $1',
 values: [i]
}))

const results = await Promise.all(queries.map(q =&gt; client.query(q)))
</code></pre>
<p>The first query sends Parse, Bind, Execute, Sync. The remaining 99 skip Parse and send only Bind, Execute, Sync. This is tracked via a <code>submittedNamedStatements</code> map that prevents duplicate Parse messages even before the server confirms the first one.</p>
<hr />
<h2><strong>Pool integration</strong></h2>
<p>Pass <code>pipeline: true</code> to the pool, and every client it creates has pipelining enabled:</p>
<pre><code class="language-javascript">const { Pool } = require('pg')

const pool = new Pool({ pipeline: true })
const client = await pool.connect()

const [r1, r2, r3] = await Promise.all([
 client.query('SELECT 1 AS num'),
 client.query('SELECT 2 AS num'),
 client.query('SELECT 3 AS num')
])

client.release()
await pool.end()
</code></pre>
<p>Note that <code>pool.query()</code> checks out a client for a single query and releases it immediately, so pipelining has no effect on that code path. Use <code>pool.connect()</code> to get a client you can pipeline on.</p>
<hr />
<h2><strong>Native client support</strong></h2>
<p><code>pg-native 3.9.0</code> also supports pipelining, using the pipeline mode API that libpq introduced in PostgreSQL 14 (<code>PQenterPipelineMode</code>, <code>PQpipelineSync</code>, <code>PQexitPipelineMode</code>). This means you need PostgreSQL 14+ client libraries installed on the machine where your application runs. The native client collects all queued queries, sends them as a single pipeline batch through libpq, and delivers results back to each query’s callback.</p>
<p>The API is identical:</p>
<pre><code class="language-javascript">const { Client } = require('pg').native

const client = new Client({ pipeline: true })
await client.connect()

// Same Promise.all pattern works
</code></pre>
<hr />
<h2><strong>PgBouncer compatibility</strong></h2>
<p>Pipelining works with PgBouncer in all pool modes: session, transaction, and statement. Since version 1.7 (December 2015), PgBouncer has tracked outstanding pipeline requests by counting Sync messages and only releases the server connection after all responses are delivered. node-postgres sends each query as a single Parse, Bind, Describe, Execute, and Sync sequence, so PgBouncer won’t reassign the connection in the middle of a query.</p>
<p>For named prepared statements through PgBouncer in transaction or statement mode, PgBouncer 1.21.0+ is required for automatic re-preparation support.</p>
<hr />
<h2><strong>Graceful shutdown</strong></h2>
<p>If you call <code>client.end()</code> while pipelined queries are still running, it waits for all of them to finish before closing the connection. This works for both the JS and native clients:</p>
<pre><code class="language-javascript">const client = new Client({ pipeline: true })
await client.connect()

const p1 = client.query('SELECT 1')
const p2 = client.query('SELECT 2')
const endPromise = client.end()

// Both queries resolve normally
const [r1, r2] = await Promise.all([p1, p2])
await endPromise
</code></pre>
<hr />
<h2>💡 When to use it</h2>
<p>Pipelining is best when you have several independent queries that don’t rely on each other’s results:</p>
<ul>
<li><p>Fetching data from several tables for a page load</p>
</li>
<li><p>Inserting or updating multiple rows simultaneously</p>
</li>
<li><p>Running a batch of analytics or reporting queries</p>
</li>
<li><p>Preloading caches or materializing views</p>
</li>
</ul>
<blockquote>
<p>Don’t use pipelining if you need to see the result of one query before sending the next. With pipelining, all queries go out before any responses return, so you can’t make decisions based on earlier results. For dependent queries in a transaction, use sequential <code>await</code> calls.</p>
</blockquote>
<hr />
<h2><strong>Try it</strong></h2>
<p>It’s out. Upgrade and flip the flag:</p>
<pre><code class="language-plaintext">npm install pg@^8.23.0
# optional, for the native client
npm install pg-native@^3.9.0
</code></pre>
<p>By default, pipelining is turned off. Upgrading does not change anything until you set <code>pipeline: true</code> on a <code>Client</code> or <code>Pool</code>. The feature works with the JS client, the native client, and the pool, and it comes with full integration tests and <a href="https://node-postgres.com/features/pipelining">documentation</a>. The pull request is <a href="https://github.com/brianc/node-postgres/pull/3652">brianc/node-postgres#3652</a>.</p>
<p>If you try pipelining and run into any issues, open an issue on the <a href="https://github.com/brianc/node-postgres/issues">node-postgres repository</a>. Real-world edge cases are what help us find and fix any remaining problems.</p>
<p>As always, if you want to learn more about <a href="https://platformatic.dev/">Platformatic</a>, <a href="https://platformatic.dev/contact">contact us</a>!</p>
]]></content:encoded></item><item><title><![CDATA[Run Nitro applications on Watt with @platformatic/nitro]]></title><description><![CDATA[Run existing Nitro and Vite+Nitro apps on Watt without changing your code. Get gateway routing, metrics, HTTPS, & coordinated scheduled tasks via ICC.]]></description><link>https://blog.platformatic.dev/run-nitro-applications-on-watt-with-platformatic-nitro</link><guid isPermaLink="true">https://blog.platformatic.dev/run-nitro-applications-on-watt-with-platformatic-nitro</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Nitro]]></category><category><![CDATA[vite]]></category><category><![CDATA[webdev]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[backend]]></category><category><![CDATA[Devops]]></category><category><![CDATA[opensource]]></category><dc:creator><![CDATA[Paolo Insogna]]></dc:creator><pubDate>Tue, 28 Jul 2026 14:36:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/91b364e3-1345-4ba1-93bf-9b492cbb7f82.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://nitro.build/">Nitro</a> is a server toolkit used by many JavaScript applications. You can use it on its own for APIs or full-stack servers, or combine it with Vite to get a familiar frontend workflow with a Nitro server in the background. Nitro also powers frameworks like Nuxt.</p>
<p>This flexibility is helpful, but running the application in production brings new challenges. A Nitro build gives you a portable Node.js server, but you still need a way to run it with other apps, expose it through a gateway, collect metrics, and make the most of your deployment’s CPU.</p>
<p><code>@platformatic/nitro</code> adds Nitro as a first-class <a href="https://docs.platformatic.dev/watt">Watt</a> capability. It lets Watt run existing Nitro applications without changing their application model. You keep Nitro’s routing, handlers, configuration, and build output. Watt takes care of the application lifecycle and the surrounding runtime.</p>
<p>This feature supports both standalone Nitro apps and Vite apps that use Nitro through <code>nitro/vite</code>. It also works with apps made by <a href="https://lovable.dev/">Lovable</a> that use this stack. Nitro’s scheduled tasks are included too. The scheduler integration lets the <a href="https://icc.platformatic.dev/">Intelligent Command Center (ICC)</a>, Platformatic’s control plane for Node.js deployments, coordinate each run across instances so that only one instance runs each task.</p>
<hr />
<h2><strong>Two ways to use Nitro</strong></h2>
<p>Nitro applications commonly arrive in one of two shapes.</p>
<p>The first is a standalone Nitro application. It uses the Nitro CLI directly:</p>
<pre><code class="language-plaintext">nitro dev
nitro build
node .output/server/index.mjs
</code></pre>
<p>The second is a Vite application that adds Nitro as a plugin. In that case, Vite runs the development server and build, then Nitro provides the production server output:</p>
<pre><code class="language-javascript">import { nitro } from 'nitro/vite'
import { defineConfig } from 'vite'

export default defineConfig({
 plugins: [nitro()]
})
</code></pre>
<p><code>@platformatic/nitro</code> figures out which setup your app uses. If your app has a Vite config file, Watt lets Vite handle development and builds. If not, it uses the standalone Nitro commands. Either way, production uses the Nitro server that gets built.</p>
<p>That distinction matters because it keeps development familiar. Vite applications retain Vite’s development server and HMR. Standalone applications retain <code>nitro dev</code>. The production target is consistent: the server Nitro creates in <code>.output</code>.</p>
<p>If you use Nuxt, keep using <code>@platformatic/nuxt</code>. Nuxt already has its own Watt feature, and Watt will detect it before using the general Nitro integration.</p>
<hr />
<h2><strong>Start with an existing application</strong></h2>
<p>Install Watt and the Nitro capability in the application:</p>
<pre><code class="language-plaintext">npm install wattpm @platformatic/nitro
</code></pre>
<p>Add a <code>watt.json</code> file:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/nitro/3.63.0.json",
 "application": {
   "basePath": "/frontend"
 }
}
</code></pre>
<p>Then use the same commands that Watt applications use elsewhere:</p>
<pre><code class="language-plaintext">wattpm dev
wattpm build
wattpm start
</code></pre>
<p>For a standalone application, basePath is passed to Nitro as <code>NITRO_APP_BASE_URL</code> during development and builds. This makes it possible to serve the application at a gateway path without hard-coding that deployment detail into the application.</p>
<p>By default, the settings match Nitro’s standard Node.js <code>output:</code> .output is the build directory and <code>server/index.mjs</code> is the production entry point. If your app uses different settings, update the capability to match.</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/nitro/3.63.0.json",
 "application": {
   "outputDirectory": "dist"
 },
 "nitro": {
   "outputDirectory": "dist",
   "entrypoint": "server/main.mjs"
 }
}
</code></pre>
<p>When you deploy, include the complete output directory. Nitro puts the server, public assets, and copied runtime dependencies there; <code>server/index.mjs</code> alone is not enough.</p>
<hr />
<h2><strong>A Nitro server in the Watt runtime</strong></h2>
<p>This feature does not replace Nitro with a different server framework. Nitro still handles all requests. Watt simply starts the server and connects it to the rest of the runtime.</p>
<p>This setup gives your Nitro app the same operational features as other Watt deployments:</p>
<ul>
<li><p>It can run beside APIs and other frontend applications in one Watt runtime.</p>
</li>
<li><p>A <a href="https://docs.platformatic.dev/docs/reference/gateway/overview">Watt gateway</a> can expose it under a base path or route traffic to it from another application.</p>
</li>
<li><p>Watt collects HTTP metrics and applies its server configuration, including production HTTPS settings. It monitors worker health and Event Loop Utilization (ELU), and can automatically recycle unhealthy workers.</p>
</li>
<li><p>Production deployments can use direct injection, connection backlog configuration, and multi-worker <code>reusePort</code> support where configured.</p>
</li>
</ul>
<p>If your team already uses Nitro, you don’t need a separate process manager or a custom deployment path. A Vite-plus-Nitro frontend can run in the same runtime as its backend services. A standalone Nitro server can join an existing Watt deployment without losing its CLI or output format.</p>
<p>Handling requests is just one part of what a Nitro app does. Nitro also runs scheduled tasks, but this can become a problem when you have more than one instance. The runtime that starts the server is best placed to solve this issue.</p>
<hr />
<h2><strong>Scheduled work without duplicate runs</strong></h2>
<p>Nitro has its own scheduler. Tasks live in tasks/, and scheduledTasks maps cron expressions to them:</p>
<pre><code class="language-typescript">// tasks/db/cleanup.ts
export default defineTask({
 meta: { name: 'db:cleanup', description: 'Remove expired records' },
 run() {
   return { result: 'ok' }
 }
})
</code></pre>
<pre><code class="language-typescript">// nitro.config.ts
import { defineConfig } from 'nitro'

export default defineConfig({
 experimental: { tasks: true },
 scheduledTasks: {
   '0 3 * * *': ['db:cleanup']
 }
})
</code></pre>
<p>On a laptop, this is exactly right: one process owns the cron expression, and <code>db:cleanup</code> runs once at 3 am. In production, the same code behaves differently. Nitro starts that timer inside every process it runs, so an application with three instances gets three cleanups, three reports, or three data imports. That is a property of the application model, not a bug: nothing in the process knows how many siblings it has.</p>
<p>Taking the schedule out of the app isn’t a good solution, since the task needs the app’s code, credentials, and internal network access. What’s needed is a single owner for the clock and a way to send each run to just one ready instance, while the work stays in the app.</p>
<p><code>@platformatic/nitro</code> provides that as a Nitro module. Add it to <code>nitro.config</code> and leave the tasks and cron expressions where they are:</p>
<pre><code class="language-typescript">// nitro.config.ts
export default defineConfig({
 experimental: { tasks: true },
 modules: ['@platformatic/nitro/scheduler'], // the only change
 scheduledTasks: {
   '0 3 * * *': ['db:cleanup']
 }
})
</code></pre>
<p>The module disables Nitro’s in-process cron runner, reports the configured task groups to Watt, and writes a scheduler manifest into the production output so the built server carries the same information. Watt registers those groups as application scheduler jobs and invokes the tasks through its internal communication channel. <code>experimental.tasks</code> has to be enabled explicitly, because Nitro scans task files before it installs modules.</p>
<p>Nothing else changes. If ICC isn’t set up, Watt schedules and runs tasks locally at the times you specify. If ICC is enabled, it coordinates when work should run, but the selected Watt instance still does the work.</p>
<p>The <a href="https://docs.platformatic.dev/docs/guides/scheduler">scheduler guide</a> covers the local configuration, and the runtime exposes the same operations over its management API (<code>GET /api/v1/scheduler</code>, plus <code>pause</code>, <code>resume</code>, and <code>run</code> for a named job). When a runtime is running, use these commands to inspect and control its jobs:</p>
<pre><code class="language-plaintext">wattpm scheduler [runtime]
wattpm scheduler:pause [runtime] &lt;name&gt;
wattpm scheduler:resume [runtime] &lt;name&gt;
wattpm scheduler:run [runtime] &lt;name&gt;
</code></pre>
<p>The optional runtime argument can be a process ID or runtime name. You can leave it out if there’s only one Watt runtime. The list command shows each job’s cron expression, source, paused state, and next run. The other commands let you pause, resume, or run a job right away.</p>
<hr />
<h3><strong>The handoff from Watt to ICC</strong></h3>
<p>The runtime provides a scheduler inventory with each job’s name, cron expression, source, paused state, and last and next execution times. It includes two kinds of work:</p>
<ul>
<li><p>Jobs configured in Watt, such as an HTTP callback to run a nightly cleanup.</p>
</li>
<li><p>Application-level jobs reported by a capability, such as Nitro scheduled tasks.</p>
</li>
</ul>
<p>An external coordinator can check the inventory, pause a local trigger without deleting it, and tell Watt to run a specific job. Even when a job is paused, it can still be run, so ICC doesn’t need to know the app’s internal callback details to dispatch it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/72ce316f-4fbe-4a95-8f37-02e33e549e2e.png" alt="" style="display:block;margin:0 auto" />

<p>Each instance reports its scheduler inventory to ICC, pauses local triggers when ICC owns scheduling, and reapplies the selected mode after a connection recovery. ICC uses the inventory to register the schedule, selects one ready instance when the cron expression fires, and sends that instance a <code>run-scheduled-job</code> command.</p>
<p>The selected instance calls Watt’s scheduler API, which runs the named job in the same runtime context it would have used locally. Configured jobs keep their callback, method, headers, and retry policy. Application jobs stay inside the capability that reported them. A failed execution is returned to ICC, which can record the failure and apply its scheduling policy; a successful run does not cause the other replicas to repeat the work.</p>
<p>This separation is useful operationally. ICC owns <a href="https://icc.platformatic.dev/intelligent-command-center/user-interface/watt-detail/scheduled-jobs/">cluster-wide scheduling</a>: one clock per job for the whole deployment rather than one clock per instance, with run history and pause-and-run-now controls exposed in the ICC user interface. It also picks a healthy target for each run. Watt and Nitro own the code that runs, application credentials, internal mesh access, and local retry behaviour. The scheduler does not need public callback URLs to reach an application in the Watt mesh, and moving a job between instances does not require copying job logic into the control plane. Execution is at least once, so scheduled handlers should be idempotent.</p>
<p>The contract is capability-neutral, so the same integration is available to Nuxt applications through <code>@platformatic/nuxt/scheduler</code>, added to <code>modules</code> in <code>nuxt.config</code> with the tasks defined in <code>server/tasks</code>. Both capabilities get the same task discovery, local and external mode switching, and on-demand execution. Runtime <code>scheduler</code> jobs, the HTTP callbacks configured in Watt itself, travel the same path, and there is a compatibility fallback for older runtime and ICC versions.</p>
<p>We plan to add scheduler coordination to all Watt features so they can use the same local and ICC-coordinated execution model.</p>
<hr />
<h2><strong>Conclusion</strong></h2>
<p><code>@platformatic/nitro</code> lets teams keep their existing Nitro apps and move them into the Watt runtime without changing the server, build, or development workflow. Both standalone services and Vite-plus-Nitro apps get the same gateway integration, metrics, HTTPS, and multi-worker production deployments.</p>
<p>If your team runs multiple instances, ICC adds a control plane to the runtime. It manages deployments and makes sure scheduled work runs only once per deployment. Your app code stays with Nitro, while Watt and ICC handle the runtime and operations.</p>
<p>The source is available in the <a href="https://github.com/platformatic/platformatic">Platformatic monorepo</a> and the <a href="https://github.com/platformatic/intelligent-command-center">ICC repository</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Stop Pinning Everything: Quantifying Upgrade Risk in Durable Workflows]]></title><description><![CDATA[Discover the Workflow Upgrade Risk (WUR) model, a data-driven approach to safely upgrading durable workflows without pinning every in-flight run.]]></description><link>https://blog.platformatic.dev/workflow-upgrade-risk-durable-workflows</link><guid isPermaLink="true">https://blog.platformatic.dev/workflow-upgrade-risk-durable-workflows</guid><category><![CDATA[workflows]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[sdk]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[research]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Luca Maraschi]]></dc:creator><pubDate>Tue, 21 Jul 2026 14:34:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/28c87b2e-b75c-4d33-a087-17e73f92e8a9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>All durable execution engines give the same versioning advice: pin your runs. Temporal pins runs to worker builds. Vercel's Workflow SDK pins each run to the deployment that started it. Azure Durable Functions recommends deploying side by side and draining old runs. The methods vary, but the idea is the same: treat every code change as risky for every in-flight run, and keep the old version running until all runs finish.</p>
<p>If your workflows finish in seconds, pinning just means a bit of wasted capacity. But for workflows that last weeks, like subscription lifecycles, compliance timers, drip campaigns, or human-in-the-loop approvals, pinning can prevent a critical bug fix from ever reaching a stuck run. You find the bug, write the fix, deploy it, but the runs that need it most never get it. That’s not a safety guarantee; it’s a liability that never goes away.</p>
<p>We’ve published a <a href="https://arxiv.org/abs/2607.13617">paper</a> that replaces this overly cautious approach with a measurable number: the <strong>Workflow Upgrade Risk (WUR)</strong> model. This model uses a static diff and existing engine telemetry to score the risk of upgrading each in-flight run from V1 to V2. There’s no need for dry-runs, sandboxes, or shadow execution. In our tests, it classified 64,920 runs with zero false negatives and can score 50,000 in-flight runs in just 0.72 seconds on a single core.</p>
<p>Below we will cover:</p>
<ol>
<li><p>Why deploying over in-flight durable workflows is dangerous in the first place.</p>
</li>
<li><p>Why the current mitigations (pinning, patch gates, side-by-side) are uniformly pessimistic</p>
</li>
<li><p>How the WUR model turns the event log into an analytical asset</p>
</li>
<li><p>The evaluation: soundness, precision, calibration, and speed</p>
</li>
</ol>
<p>Let’s get started.</p>
<hr />
<h2>The determinism contract and its corollary</h2>
<p>Here’s a quick refresher on how durable execution works. Engines like Temporal, Azure Durable Functions, Restate, and the Workflow SDK keep an append-only log of events, such as step invocations, results, timers, and external signals. If a process needs to resume after a crash, suspension, or redeployment, the engine re-executes the orchestration function from the start and uses the recorded results for completed steps. The run doesn’t repeat side effects; it just replays decisions. This works because of a determinism contract: if the event history is the same, the orchestration code must always make the same decisions. There’s an important point that often gets overlooked: the event log only makes sense in the context of the code that created it. If you deploy V2 while runs started under V1 are still active, you can run into three types of failures:</p>
<ol>
<li><p><strong>Replay divergence.</strong> V2 reaches a different step than the log expects because a step was inserted, removed, or reordered. Best case, the engine throws a hard nondeterminism error. Worst case, it silently substitutes the wrong recorded result into the wrong call site.</p>
</li>
<li><p><strong>Rehydration failure.</strong> A recorded payload no longer satisfies the shape V2's downstream code consumes. A field was removed, renamed, or its type narrowed, and the run faults mid-replay.</p>
</li>
<li><p><strong>Behavioural drift.</strong> Replay succeeds, but the steps not yet executed behave differently under V2. The run completes with semantics neither version's author intended.<br />The rules that cause these failures are stricter than you might expect. In engines that use ordinal identity, each site is identified by a pair: the global invocation order and the name. This sequence is shared across steps, timers, and hooks. If you add a step at the end of a workflow, every recorded event still matches up, so nothing breaks. But if you add a step at the beginning, every following ordinal shifts, and replay diverges right away for any run that has already started. The same change can have opposite effects, and you won’t notice unless you check each run.</p>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/6ef890d1-058c-464e-b202-435c2314d1f7.png" alt="" style="display:block;margin:0 auto" />

<p><em>If you replay the same recorded log against two versions, adding a step at the end keeps all the ordinals matched. But adding a step at the beginning shifts every ordinal after it, causing replay to diverge on the first event.</em></p>
<hr />
<h3><strong>Why pin-by-default is the wrong default</strong></h3>
<p>The state of the art here is operational, not analytical. Temporal offers <code>patched()</code> markers and worker build IDs. The Workflow SDK pins by default and offers a <code>deploymentId: "latest"</code> escape hatch that explicitly delegates the compatibility judgment to you. Restate's docs enumerate the unsafe change classes and then leave the per-run decision to human judgment.</p>
<p>These methods are reliable, but they’re also overly cautious. They assume every change is incompatible with every in-flight run, even though most changes aren’t. For example, editing the body of a step doesn’t affect replay. Adding a step at the end doesn’t break anything. Consuming a new field only causes problems for runs whose recorded payload is missing that field, and you can check that in your database right now.</p>
<p>This cautious approach adds up over time. Temporal’s <code>patched()</code> helps with mixed-version execution, but patches pile up, and you can only remove a patch when you’re sure no in-flight run can still use the old branch. That’s a probability question about your fleet, but no one calculates it today. Meanwhile, every pin-by-default deployment keeps old versions running, building up what the paper calls forgone-fix exposure: the chance that a stuck run hits the exact bug V2 was meant to fix.</p>
<p>Here’s the question no one was answering: given the difference between V1 and V2, and the telemetry your engine already saves, what’s the chance that upgrading a specific in-flight run will fail?</p>
<hr />
<h3><strong>Turning the durability guarantee into a risk model</strong></h3>
<p>Our main insight is that event-sourced workflow engines are especially well-suited for analyzing change risk. In most distributed systems, risk models have to guess interaction patterns from samples. But here, the protocol saves complete histories, every path taken and every payload produced, because of its durability guarantee. You’ve already paid for the storage, and the WUR model turns that into a valuable analytical tool.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/fdc354dd-ba6d-48ea-bac8-3b13644730ad.png" alt="" style="display:block;margin:0 auto" />

<p><em>There are two separate tracks: the static track classifies the diff without running any code, and the telemetry track rebuilds each run’s state without looking at the source. At no point does the system replay a log against V2.</em></p>
<p>Risk decomposes into two components that differ in kind:</p>
<p><strong>Backward risk: can the recorded history rehydrate under V2?</strong> This is computed exactly, not estimated. The run's prefix is fully known, so the model checks whether the prefix maps to a valid path in V2's step graph and validates every recorded payload against V2's actual demands. In the exact regime, backward risk is a verdict in {0, 1}, and the paper proves a certification theorem: a zero backward-risk verdict guarantees that replay under V2 succeeds and suspends at the matched frontier with the same substituted values. Not “probably fine.” Proven safe.</p>
<p><strong>Forward risk: will the remainder of the run traverse changed code?</strong> This part is genuinely probabilistic, so the model estimates it honestly. Complete path histories yield an empirical Markov chain over the step graph; hitting probabilities from the run's current frontier to each changed site, weighted by a severity estimated from telemetry (retry logs give you an empirical idempotency measure, deployment history calibrates severity per change class), compose into a forward score.</p>
<p>The model uses Bayesian estimation, so every WUR score comes with a credible interval. If you don’t have much telemetry, the model won’t give you a confident but wrong answer—it will just give you a wide interval. That’s useful on its own: it tells you there isn’t enough data to safely approve this migration.</p>
<p>Two design choices make a big difference:</p>
<p><strong>No code execution, ever.</strong> The pivotal substitution is that payload compatibility is not a property of code paths you must exercise. It is a measure-theoretic property of the observed payload distribution against a static contract. If V2 newly destructures field x, the incompatibility rate is exactly the recorded absence rate of x. Data validated against a schema, no sandbox required.</p>
<p><strong>Precision spent only where the diff spends risk.</strong> The differential-demand lemma says that if a consumer slice is unchanged between versions, history itself is the compatibility proof: the run already consumed that payload with that exact code and did not fault. Contract inference is confined to the handful of access paths a release actually changes.</p>
<hr />
<h3><strong>Migrate, review, pin</strong></h3>
<p>The scores support a three-way policy. Runs with zero backward risk and very low forward risk can mov<strong>e</strong> to V2. Runs with some but uncertain forward risk go to <strong>review</strong>, ranked by expected loss. Runs with any backward risk are pinned, but now pinning is a measured cost, not the default. You can calculate expected drain time from the same Markov chain, so if a release leaves runs stuck behind a 90-day sleep, you’ll see that risk up front, not as a surprise later.</p>
<p>A worked example from the paper makes the granularity concrete. A linear-order workflow (validate, charge, sleep 24h, notify, archive) ships a V2 in which archive now consumes charge.promoCode, a field present in 56.7% of historical runs. Four in-flight runs, one change, three different verdicts:</p>
<table style="min-width:428px"><colgroup><col style="min-width:25px"></col><col style="width:109px"></col><col style="width:105px"></col><col style="width:85px"></col><col style="width:104px"></col></colgroup><tbody><tr><td><p><strong>Run (state at suspension)</strong></p></td><td><p><strong>Backward</strong></p></td><td><p><strong>Forward</strong></p></td><td><p><strong>WUR</strong></p></td><td><p><strong>Verdict</strong></p></td></tr><tr><td><p>r1: before charge</p></td><td><p>0.00</p></td><td><p>0.43</p></td><td><p>0.43</p></td><td><p>review</p></td></tr><tr><td><p>r2: charged, promoCode recorded</p></td><td><p>0.00</p></td><td><p>0.00</p></td><td><p>0.00</p></td><td><p>migrate</p></td></tr><tr><td><p>r3: charged, promoCode absent</p></td><td><p>0.00</p></td><td><p>1.00</p></td><td><p>1.00</p></td><td><p>pin</p></td></tr><tr><td><p>r4: complete prefix, promo present</p></td><td><p>0.00</p></td><td><p>0.00</p></td><td><p>0.00</p></td><td><p>migrate</p></td></tr></tbody></table>

<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/4c4b3a45-c917-4520-bde9-0eec51e6cd5a.png" alt="" style="display:block;margin:0 auto" />

<p><em>One change, four runs, three different outcomes. r2 and r3 are at the same point, but the verdict is different because the model checks each run’s recorded state.</em></p>
<p>r2 and r3 are at the same point under the same change, but the difference comes from their recorded payloads, which the model checks. Only r1, which needs a payload that doesn’t exist yet, has real probabilistic risk (0.43 is the measured absence rate). So instead of pinning every run, this rollout only leaves one run stranded.</p>
<p>There’s another layer to consider, since production fleets aren’t just collections of independent runs. Workflows can signal each other, create child runs, and share resources. Any real-world split between migrate and pin creates a window where connected runs are running different code but sharing channels. The model builds a coupling graph from tokens already in the logs, tracks how failures can spread, and calculates the best migrate/pin split using a minimum s-t cut. Saga partners only cross versions when the costs make sense, just like a careful human operator would, but now it’s computed, not guessed.</p>
<hr />
<h3><strong>The numbers</strong></h3>
<p>We validated the model three ways: a controlled scenario suite, a mutation study, and a hand-translated corpus of real workflows from the Workflow SDK's own repository <em>(45 workflow functions spanning sagas, fan-out, human-in-the-loop approval, parent-child hierarchies, webhooks, and durable agents)</em>.</p>
<p>The headline results:</p>
<table style="min-width:284px"><colgroup><col style="min-width:25px"></col><col style="width:259px"></col></colgroup><tbody><tr><td><p><strong>Metric</strong></p></td><td><p><strong>Result</strong></p></td></tr><tr><td><p>False negatives (synthetic, 64,920 verdicts)</p></td><td><p>0</p></td></tr><tr><td><p>False negatives (real corpus, 18,160 verdicts)</p></td><td><p>0</p></td></tr><tr><td><p>Precision, synthetic mutations</p></td><td><p>0.815</p></td></tr><tr><td><p>Precision, real-workflow corpus</p></td><td><p>0.933</p></td></tr><tr><td><p>Calibration error, distributional regime</p></td><td><p>0.016 ECE, 0.92 correlation</p></td></tr><tr><td><p>Backward risk per run</p></td><td><p>9 to 15 µs</p></td></tr><tr><td><p>50,000-run fleet classification</p></td><td><p>0.72 s, one core</p></td></tr></tbody></table>

<p>A recall of exactly 1.0 is what the certification theorem requires, and the evaluation is clear about what that means: it checks the implementation against verified replay behaviour, not against failures outside the model’s scope. Every false positive has a clear cause, usually from conservative predicate matching, and each cause can be targeted for annotation. For example, predicate-equivalence hints alone would remove 86% of the synthetic false positives. Most importantly, the model only errs in one direction. A false positive just pins a run that was actually safe, costing you some drain time. A false negative would corrupt state. The design chooses the first to make the second impossible, and then measures what that caution costs.</p>
<p>The calibration result is important for teams that don’t keep full payloads. Just knowing how often a field is present gives a good risk estimate, and you can get useful predictions with just tens of completed runs, not thousands.</p>
<hr />
<h3><strong>Why we built this</strong></h3>
<p>This isn’t just theory. Platformatic ICC already uses version-aware traffic control and skew protection for Node.js fleets, and our predictive autoscaler <em>(which we covered in our</em> <a href="https://blog.platformatic.dev/ahead-of-time-scaling-platformatic-icc-predictive-autoscaling"><em>previous deep dive</em></a><em>)</em> is based on the same idea: infrastructure decisions should be driven by real measurements from your system, not by static thresholds or worst-case guesses.</p>
<p>Autoscaling and upgrade management face the same problem today. Reactive scalers treat every metric snapshot separately, and pin-by-default versioning treats every deploy as extremely risky. Both approaches waste money because they lack a real model. The solution is the same for both: use the telemetry you already have to make informed decisions instead of guessing.</p>
<p>For durable workflows, the costs are clear. Every pinned run means you’re paying for old-version capacity and still exposed to bugs you’ve already fixed. The WUR model puts a price on both, for each run, before you deploy. It also lets you split releases, since risk is provably sub-additive across changes. This means you can break up a release into smaller deploys, each within a risk budget. The common wisdom that small, frequent deploys are safer is now backed by theory.</p>
<hr />
<h3><strong>What's next</strong></h3>
<p>The reference implementation is a single-file analyzer that only needs run listings and event logs. It comes with the paper, the full experiment suite, and the hand-translated corpus. The most valuable experiment is one we can’t do alone: validating the model against real production deployment histories by replaying past releases with known outcomes. That telemetry is with platform operators, which is exactly where the model is meant to be used.</p>
<p>If you run a durable execution platform or manage long-lived workflows and are tired of choosing between stranded runs and risky deploys, we’d love to hear from you.</p>
<ul>
<li><p><a href="https://arxiv.org/abs/2607.13617">Full White Paper</a></p>
</li>
<li><p><a href="https://icc.platformatic.dev/">Platformatic ICC</a></p>
</li>
<li><p>Drop us a note at <a href="mailto:hello@platformatic.dev">hello@platformatic.dev</a> or reach out on LinkedIn.</p>
</li>
</ul>
<p>Thank you, and happy building!</p>
]]></content:encoded></item><item><title><![CDATA[Run Durable Eve Agents on Kubernetes with Platformatic]]></title><description><![CDATA[How to run durable Eve AI agents on Kubernetes with Platformatic, using Workflow SDK, Watt, and ICC for reliable, version-safe execution.]]></description><link>https://blog.platformatic.dev/run-durable-eve-agents-on-kubernetes-with-platformatic</link><guid isPermaLink="true">https://blog.platformatic.dev/run-durable-eve-agents-on-kubernetes-with-platformatic</guid><category><![CDATA[ai agents]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Vercel]]></category><dc:creator><![CDATA[Paolo Insogna]]></dc:creator><pubDate>Thu, 16 Jul 2026 14:52:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/54e501e4-97b4-4c11-93a2-8f001f419541.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://vercel.com/eve">Eve</a> organizes AI agents in a simple way: use Markdown for instructions and skills, TypeScript for tools, and separate files for channels, schedules, and subagents. Behind this setup, Eve relies on the open-source <a href="https://workflow-sdk.dev/">Workflow SDK</a> to keep every session durable. This means an agent can call a tool, wait for user input, survive restarts, and pick up right where it left off.</p>
<p>Eve runs smoothly on Vercel, which handles the workflow runtime, queues, storage, and sandbox setup for you. This is the easiest option if you already use Vercel for deployment. If you are not on Vercel, Eve uses the Workflow SDK’s Local World by default. Local World saves state on your local filesystem and processes steps one at a time. This works well for development, but it does not offer shared state, distributed queues, or deployment-version routing needed for production environments.</p>
<p>Teams running applications in their own Kubernetes clusters need a production path that keeps Eve’s programming model while running its application and durable workflow infrastructure in the environment they already operate.</p>
<p>You now have two options for running Eve with Platformatic. For standalone agents, the new <a href="https://github.com/platformatic/eve">@platformatic/eve</a> capability lets you build and run Eve as a Watt application. If your agent is part of a Next.js app, <code>@platformatic/next</code> runs the Next.js application, and Eve connects directly using its <code>withEve()</code> adapter. Both setups can use @platformatic/world to connect to a self-hosted Workflow Service. On Kubernetes, <a href="https://icc.platformatic.dev/">Platformatic ICC</a> adds features like application lifecycle management, scaling, and workflow-aware <a href="https://icc.platformatic.dev/skew-protection/">Skew Protection.</a> Existing runs stay on the version they started with, while new runs use the latest deployment.</p>
<p>You still write your Eve agent the same way. Only the deployment target changes, not the agent model.</p>
<hr />
<h2><strong>What an Eve agent looks like</strong></h2>
<p>Eve is designed to work with the filesystem. For example, a weather agent can be set up as a directory with just four small files:</p>
<pre><code class="language-plaintext">agent/
|-- instructions.md
|-- agent.ts
|-- channels/
|   `-- eve.ts
`-- tools/
   `-- get_weather.ts
</code></pre>
<p><code>instructions.md</code> defines the agent’s role. <code>agent.ts</code> selects and configures the model. Each file under <code>tools/</code> becomes a typed tool, and channel files expose the agent over HTTP, Slack, Discord, or another supported interface.</p>
<p>Eve turns each message into a durable workflow. It records model calls, tool calls, streamed events, waits, and user responses as part of the session. If a process stops in the middle of a turn, another process can pick up from the last completed step instead of starting over.</p>
<p>This is why production needs more than just an HTTP server. Durable execution requires persistent state, queues, retry handling, and a way to route resumed work to code that can still run it.</p>
<hr />
<h2><strong>Running Eve as a standalone Watt application</strong></h2>
<p>The simplest deployment uses <code>@platformatic/eve</code> directly. This capability manages Eve’s development server, runs its build pipeline, loads its production Nitro output, and exposes the application through Watt.</p>
<p>The Platformatic configuration is short:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/eve/0.0.1.json",
 "module": "@platformatic/eve",
 "server": {
   "hostname": "0.0.0.0",
   "port": "{PORT}"
 }
}
</code></pre>
<p>The usual Watt commands cover the full lifecycle:</p>
<pre><code class="language-plaintext">wattpm dev
wattpm build
wattpm start
</code></pre>
<p>Besides starting Eve, this capability connects it to Platformatic’s runtime. It uses Watt’s server settings, manages the agent with Watt’s application lifecycle, and collects HTTP metrics. You can package the production output in the same container and deployment pipeline as your other Watt applications, so you do not need a separate hosting model for the agent.</p>
<p>The <a href="https://github.com/platformatic/eve/tree/main/demos/weather-assistant">demos/weather-assistant</a> example uses Eve’s weather agent and runs it in this way. It includes one typed tool and an HTTP channel, making it a helpful reference that does not hide the integration behind a bigger application.</p>
<hr />
<h2><strong>Running Eve inside a Next.js application</strong></h2>
<p>Often, an agent fits better inside an existing product instead of running behind a separate public endpoint. The <a href="https://github.com/platformatic/eve/tree/main/demos/next-eve-platformatic-world">demos/next-eve-platformatic-world</a> example shows how to set this up.</p>
<p>Next.js runs on Watt through <code>@platformatic/next</code>, while Eve’s official <code>withEve()</code> integration provides the agent API. <code>@platformatic/eve</code> is not involved in this deployment path. The browser talks to the Next.js application, and Next forwards Eve session requests to the internal Eve process. A second rewrite forwards Workflow SDK callbacks:</p>
<pre><code class="language-javascript">import { withEve } from 'eve/next'

const eveOrigin = `http://127.0.0.1:${process.env.EVE_NEXT_PRODUCTION_PORT ?? '4274'}`

const nextConfig = {
 async rewrites() {
   return {
     beforeFiles: [
       {
         source: '/.well-known/workflow/:path+',
         destination: `${eveOrigin}/.well-known/workflow/:path+`
       }
     ]
   }
 }
}

export default withEve(nextConfig)
</code></pre>
<p>The Next.js UI and Eve agent stay in the same project, image, and Kubernetes pod. Watt manages the Next.js application, while the internal Eve process handles session and workflow routes. This setup keeps the agent close to the application that uses it, without combining both runtimes into a single server.</p>
<p>Embedding Eve does not skip Watt. The Next.js application still runs with <code>@platformatic/next</code>, keeping Watt’s production runtime, application lifecycle management, HTTP metrics, health monitoring, gateway integration, and ICC support. ICC can monitor and scale the pod as a Watt deployment, and <code>@platformatic/world</code> connects Eve to the Workflow Service. This way, your application uses Eve’s agent model without losing the operational benefits from Watt or moving the Next.js deployment outside your existing infrastructure.</p>
<p>Both deployment styles use the same Eve project layout. Your choice depends on your needs: you can deploy a focused agent service or include the agent with the Next.js application where users interact with it.</p>
<hr />
<h2><strong>Replacing Vercel’s hosted workflow infrastructure with</strong> <code>@platformatic/world</code></h2>
<p>Eve uses the Workflow SDK’s World abstraction for session state, queues, hooks, waits, and streams. On Vercel, it can select Vercel World automatically. To run that infrastructure yourself, select <code>@platformatic/world</code> and point it to the Workflow Service provided by <code>@platformatic/workflow</code>:</p>
<pre><code class="language-plaintext">WORKFLOW_TARGET_WORLD=@platformatic/world
PLT_WORLD_SERVICE_URL=http://localhost:3042
</code></pre>
<p>The <code>@platformatic/world</code> client sends workflow operations to the Workflow Service. This service stores workflow state in PostgreSQL and manages queue delivery, retries, hooks, waits, streams, and deployment lifecycle data. You can set <code>PLT_WORLD_SERVICE_URL</code> to a local service during development or to an internal address in your production environment.</p>
<p>The Workflow Service does not need ICC. It can run by itself with PostgreSQL for local development, CI, or self-managed deployments. This is helpful if you want durable Eve sessions while keeping the database, queue routing, and application inside your existing network and security setup.</p>
<p>ICC comes into play when your application runs in Kubernetes. Pods use their ServiceAccount tokens to authenticate, and ICC handles application provisioning, workflow handler registration, and deployment version management as versions move from active to draining and expired. The World client and Workflow Service stay the same, but ICC adds the Kubernetes control plane around them.</p>
<p>Model routing is equally portable. An Eve agent can pass an AI SDK provider model directly:</p>
<pre><code class="language-javascript">import { anthropic } from '@ai-sdk/anthropic'
import { defineAgent } from 'eve'

export default defineAgent({
 model: anthropic('claude-sonnet-5')
})
</code></pre>
<p>The same flexibility applies to sandboxes. Eve can use local Docker, microsandbox, just-bash, or a custom backend. You can set up model routing, sandbox execution, workflow state, and application hosting to match your own infrastructure needs.</p>
<hr />
<h2><strong>Distributing steps across pods and workers</strong></h2>
<p>A durable agent session is made up of a series of queued operations, not a single long request tied to one Node.js process. This approach increases your execution capacity.</p>
<p>Each queue message handled by the Workflow Service includes the deployment version for its run. The Workflow Service sends the message to the Kubernetes Service registered for that version. Kubernetes can pick any ready pod behind that Service, and Watt can accept the connection on any configured application worker in the pod. This means different steps in a session can run on different pods and Watt workers, all while sharing the same durable state.</p>
<p>A session is tied to a deployment version, not to a specific pod or worker. This setup keeps code-version correctness while still allowing horizontal scaling and Watt’s multithreaded execution.</p>
<p>This design avoids sending every agent session through a single Node.js thread. Adding more pods increases your cluster’s capacity, and adding Watt workers lets each pod use its CPU cores. Distribution uses normal connection load balancing, so all eligible pods and workers can participate. The workflow uses your cluster’s existing capacity instead of relying on a provider-specific execution tier.</p>
<p>This design also helps with failure recovery. If a worker stops while handling a step, the queue retries the operation. A restarted worker or another worker in the deployment can take over. If a pod goes away, Kubernetes can send the retry to another ready pod. The durable event history and stable tool call identity let the workflow continue without treating a process failure as the end of the session.</p>
<p>The <a href="https://github.com/platformatic/eve/tree/main/demos/workflow-distribution-agent">demos/workflow-distribution-agent</a> example shows this in action. It records the pod, Watt worker, and worker thread for each stage, then intentionally crashes selected workers to confirm that queued work finishes elsewhere.</p>
<hr />
<h2><strong>One workflow, one code version</strong></h2>
<p>Distributing work creates a second problem during deployments. A workflow may start on version 1, pause for a tool or human response, and resume after version 2 has become active. Replaying version 1’s event history against changed version 2 code can call steps in the wrong order or apply stored results to the wrong operation.</p>
<p>We introduced the underlying version-pinning model in <a href="https://blog.platformatic.dev/durable-workflows-kubernetes-version-safe">our Platformatic World launch post</a>, which explains why deterministic workflow replay must return to the code version that created the run.</p>
<p>The Workflow Service records the deployment version when the run starts. Every later queue message for that run carries the same version. When version 2 deploys, ICC marks version 1 as draining and sends new sessions to version 2, but the Workflow Service continues routing version 1’s steps to version 1 pods.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/85323a95-b251-4753-aac6-a6586379f2eb.png" alt="" style="display:block;margin:0 auto" />

<p>ICC does not decide that a workflow version is idle from HTTP traffic alone. A run may be sleeping, waiting for a webhook, or paused for human approval without producing traffic or queue messages. ICC asks the Workflow Service for active runs, pending hooks, waits, and queued messages. It keeps the draining deployment available while any of those counts are non-zero.</p>
<p>This setup gives you a clear guarantee: a workflow starts, resumes, and finishes on the same application version, even if new versions are deployed while it is running. New workflows use the latest active version, while older workflows keep the code they started with until they finish or reach the forced-expiration limit you set.</p>
<hr />
<h2><strong>Operating Eve agents through ICC</strong></h2>
<p>After deployment, the Watt application hosting Eve shows up in ICC just like other Watt applications. ICC collects runtime metrics, tracks deployments, and can scale the application based on Node.js signals like Event Loop Utilization. Operations stay within the same control plane your team uses for other Kubernetes workloads.</p>
<p>ICC also reads workflow data from the Workflow Service. The Workflows view lists runs by status and deployment version. Each run detail page shows its execution trace, step graph, events, hooks, and streams. Operators can replay a run on its original deployment version, cancel a run, or wake a sleeping workflow from the same interface.</p>
<p>This setup bridges the gap between building an agent and running it in production. Eve provides the agent framework, Watt runs the application, the Workflow Service handles durable distributed execution, and ICC manages the Kubernetes lifecycle.</p>
<hr />
<h2><strong>Conclusion</strong></h2>
<p>At the infrastructure level, <code>@platformatic/world</code> and the Workflow Service provide durable Eve sessions backed by PostgreSQL. You can run them without ICC for local development, CI, or in a self-managed environment.</p>
<p>At the application level, a standalone agent uses <code>@platformatic/eve</code> as its Watt capability. If the agent is embedded in Next.js, it uses Eve’s <code>withEve()</code> integration directly, while <code>@platformatic/next</code> keeps the application on Watt and preserves its runtime and operation.</p>
<p>When you move these applications to Kubernetes, ICC adds deployment management, scaling, and workflow-aware skew protection. Workflow steps can use available pods and, for standalone Watt agents, the configured workers. Retries help recover from process failures, and every run stays on the code version it started with. New deployments get new sessions as older versions finish their current work in progress.</p>
<p>You keep Eve’s instructions, tools, skills, channels, and durable sessions. Platformatic provides the runtime,</p>
<p>distributed execution, deployment lifecycle, and Kubernetes operations. Your application can run anywhere you use Kubernetes, including private cloud and on-premises environments.</p>
<p>The source and demos are available in the <a href="https://github.com/platformatic/eve">platformatic/eve</a> repository. The source for <code>@platformatic/world</code> and the Workflow Service is available from <a href="https://github.com/platformatic/platformatic-world">platformatic/platformatic-world</a>.</p>
<p>If you’re planning to build agents and host on K8s, drop us a note at <a href="mailto:hello@platformatic.dev">hello@platformatic.dev</a> or reach out on LinkedIn.</p>
]]></content:encoded></item><item><title><![CDATA[Stop Request Stampedes at the Gateway with Platformatic Deduplication]]></title><description><![CDATA[Learn how Platformatic Gateway request deduplication prevents thundering herd traffic, reduces upstream load, and improves Next.js performance.]]></description><link>https://blog.platformatic.dev/gateway-request-deduplication-nodejs</link><guid isPermaLink="true">https://blog.platformatic.dev/gateway-request-deduplication-nodejs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[api]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[performance]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[caching]]></category><category><![CDATA[Devops]]></category><category><![CDATA[scalability]]></category><dc:creator><![CDATA[Paolo Insogna]]></dc:creator><pubDate>Tue, 30 Jun 2026 14:38:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/bf8ab33e-f186-408d-b099-2cff8747d25f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Picture an online store launching a new product and sending out a mailing list campaign. Thousands of users click the same link at once. The product page, built with a Node.js app like Next.js, needs to fetch the same product details, inventory, recommendations, and pricing for each request.</p>
<p>If the page is cached, everything works smoothly. Problems begin when the cache is empty, expired, or being refreshed. Then, the first group of users all miss the cache together, and every request asks the app to generate the same response. (This same thing would also happen with a trending news story, a search crawler, frontend prefetching, or after a cache reset.)</p>
<p>This situation is known as the “thundering herd” problem. Every user request is valid, but the work gets repeated. Your app uses CPU, database, and network resources to calculate the same result over and over, just when response times are already strained.</p>
<p>Rather than sending all traffic straight to your app, wouldn’t it be great if you could place a gateway in front that spots duplicate in-flight reads and combines them before they hit Node.js?</p>
<p>Platformatic Gateway now does exactly this. With request deduplication, it merges concurrent requests for the same data. Only one goes upstream, while the others wait and then get the same response.</p>
<p>This is not a replacement for caching. Instead, it acts as a short-term coordination layer for requests in progress. The cache handles future requests, while deduplication shields your app while the first response is still being generated.</p>
<p>This is especially important for self-hosted Next.js apps. A popular route can cause heavy server rendering, React Server Component processing, image metadata checks, or backend API calls. When many users hit that route at once, or during cache refreshes, deduplication stops the gateway from sending the same work to Next.js over and over.</p>
<hr />
<h2><strong>A Local Benchmark</strong></h2>
<p>To see how much this helps, we ran a simple local test with a purposely slow route behind a proxy. The upstream route waited 100 ms before responding, simulating a page or API call that needs backend work. The test used the same leader/waiter pattern as gateway deduplication and sent 100 requests at once to the same URL.</p>
<p>These are the median numbers from three runs:</p>
<table style="width:685px"><colgroup><col style="width:142px"></col><col style="width:101px"></col><col style="width:114px"></col><col style="width:114px"></col><col style="width:123px"></col><col style="width:91px"></col></colgroup><tbody><tr><td><p><strong>Scenario</strong></p></td><td><p><strong>Client requests</strong></p></td><td><p><strong>Upstream requests</strong></p></td><td><p><strong>Average latency</strong></p></td><td><p><strong>p99 latency</strong></p></td><td><p><strong>Errors</strong></p></td></tr><tr><td><p>Without deduplication</p></td><td><p>1,000</p></td><td><p>1,000</p></td><td><p>111.31 ms</p></td><td><p>134 ms</p></td><td><p>0</p></td></tr><tr><td><p>With deduplication</p></td><td><p>1,000</p></td><td><p>10</p></td><td><p>104.88 ms</p></td><td><p>127 ms</p></td><td><p>0</p></td></tr><tr><td><p>Without deduplication</p></td><td><p>10,000</p></td><td><p>10,000</p></td><td><p>104.80 ms</p></td><td><p>122 ms</p></td><td><p>0</p></td></tr><tr><td><p>With deduplication</p></td><td><p>10,000</p></td><td><p>100</p></td><td><p>102.91 ms</p></td><td><p>106 ms</p></td><td><p>0</p></td></tr></tbody></table>

<p>The key result isn’t the slight change in average latency, but the number of upstream requests. With deduplication, the proxy still answers every client, but the upstream app only processes one response per wave of requests. In a test with 10,000 requests, that meant just 100 upstream responses instead of 10,000. In real situations, this can mean the difference between a burst that overwhelms your app and one that the gateway handles smoothly.</p>
<hr />
<h2><strong>How It Works</strong></h2>
<p>Gateway deduplication uses a leader/waiter model that is easy to reason about in production.</p>
<p>The first matching request becomes the leader. It acquires a lock, goes to the upstream application, buffers the response, stores it for a short time, and notifies any waiters. Concurrent requests with the same key become waiters. They do not call the upstream service immediately; instead, they wait for the leader response and replay it when it becomes available.</p>
<p>In a production gateway, deduplication often sits next to caching. You can use separate Valkey instances or separate key prefixes in the same Valkey deployment, but the two stores serve different purposes: cache storage keeps reusable responses, while deduplication storage keeps short-lived locks and response buffers for in-flight requests.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/87504c18-e5e8-4763-a428-95b8508848ea.png" alt="" style="display:block;margin:0 auto" />

<p>To prevent deadlocks, every coordination point has an expiration. The leader lock uses a <code>lockTtl</code>, waiters have a <code>timeout</code>, and retries are limited. If the leader fails, the lock expires, a waiter times out, or retries run out, the request switches back to normal proxying. This fallback is intentional—deduplication is meant to lower load, not cause requests to get stuck during traffic spikes.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/9fe7db00-4342-4464-b99c-f16306f36587.png" alt="" style="display:block;margin:0 auto" />

<p>For a single request, the decision path looks like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/60845246-b8d2-4ce5-8d12-2707ea319098.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2><strong>The Simplest Configuration</strong></h2>
<p>Enable deduplication globally under <code>gateway.deduplication:</code></p>
<pre><code class="language-json">{
  "gateway": {
    "deduplication": {
      "enabled": true
    },
    "applications": [
      {
        "id": "frontend",
        "proxy": {
          "prefix": "/"
        }
      }
    ]
  }
}
</code></pre>
<p>By default, deduplication works for <code>GET</code> and <code>HEAD</code> requests and uses <code>memory</code> for storage.</p>
<p>This default is intentionally cautious. <code>GET</code> and <code>HEAD</code> are the safest types of requests to deduplicate. Write requests often need custom rules before they can be safely coordinated.</p>
<hr />
<h2><strong>Per-Application Overrides</strong></h2>
<p>You can also configure deduplication per proxied application with <code>gateway.applications[].proxy.deduplication</code>. Application-level options override the global options.</p>
<pre><code class="language-json">{
 "gateway": {
   "deduplication": {
     "enabled": true,
     "methods": ["GET"]
   },
   "applications": [
     {
       "id": "frontend",
       "proxy": {
         "prefix": "/",
         "deduplication": {
           "enabled": true,
           "routes": [{ "method": "GET", "path": "/blog/*" }]
         }
       }
     }
   ]
 }
}
</code></pre>
<p>This approach lets you begin where the benefits are clear. You can deduplicate public catalogue pages, blog posts, product details, or framework prefetch routes, while keeping endpoints with strict per-user behaviour unchanged.</p>
<hr />
<h2><strong>Choosing The Deduplication Key</strong></h2>
<p>The default key is computed from:</p>
<ul>
<li><p>the configured application origin</p>
</li>
<li><p>the HTTP method</p>
</li>
<li><p>the rewritten proxy URL, including the query string</p>
</li>
<li><p>selected request headers</p>
</li>
</ul>
<p>The default headers are:</p>
<pre><code class="language-plaintext">["authorization", "cookie", "accept", "accept-language"]
</code></pre>
<p>Including headers matters because many read responses are not only a function of the URL. A localized page can depend on accept-language. A user-specific page can depend on <code>cookie</code> or <code>authorization</code>. If those headers were ignored, unrelated callers could incorrectly share a response.</p>
<p>You can adjust the headers included in the key for a deduplication configuration:</p>
<pre><code class="language-json">{
 "gateway": {
   "deduplication": {
     "enabled": true,
     "headers": ["authorization", "cookie", "x-tenant-id"]
   }
 }
}
</code></pre>
<p>Currently, you can’t set headers per route. If you need different header behaviour for different routes, use separate deduplication settings for each application or create a custom key function.</p>
<p>For full control, provide a synchronous key function:</p>
<pre><code class="language-json">{
 "gateway": {
   "deduplication": {
     "enabled": true,
     "key": "./deduplication-key.js"
   }
 }
}
</code></pre>
<pre><code class="language-javascript">export function computeDeduplicationKey(request, context) {
 return `${context.origin}:${context.method}:${context.url}`
}
</code></pre>
<p>The function receives the request and a context object containing the origin, method, rewritten URL, parsed query, selected headers, and application configuration. It must return the key synchronously.</p>
<hr />
<h2><strong>Route Whitelisting</strong></h2>
<p>For tighter control, configure a route whitelist. Routes use <a href="https://github.com/delvedor/find-my-way">find-my-way</a> syntax.</p>
<pre><code class="language-json">{
 "gateway": {
   "deduplication": {
     "enabled": true,
     "routes": [
       { "method": "GET", "path": "/blog/*" },
       { "methods": ["GET", "HEAD"], "path": "/products/:id" }
     ]
   }
 }
}
</code></pre>
<p>When <code>routes</code> are configured, route matching decides whether deduplication applies. When <code>routes</code> are not configured, the <code>methods</code> list decides.</p>
<hr />
<h2><strong>Storage: Memory Or Valkey</strong></h2>
<p>TBy default, memory is used for storage. It handles duplicate requests within a single gateway instance and doesn’t need any external service. This setup is great for local development, single-instance deployments, and easy rollouts.</p>
<pre><code class="language-json">{
 "gateway": {
   "deduplication": {
     "enabled": true,
     "storage": {
       "adapter": "memory"
     }
   }
 }
}
</code></pre>
<p>For deployments that scale horizontally, use the valkey adapter. It stores locks, response pointers, and buffered responses in a Redis-compatible Valkey server, allowing multiple gateway workers, instances, or pods to coordinate. This way, you get the same deduplication benefits even when traffic is spread across several replicas.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/860d66e5-8f7d-4f7a-a2e3-c04094af5abf.png" alt="" style="display:block;margin:0 auto" />

<pre><code class="language-json">{
 "gateway": {
   "deduplication": {
     "enabled": true,
     "storage": {
       "adapter": "valkey",
       "url": "redis://127.0.0.1:6379",
       "prefix": "my-application"
     }
   }
 }
}
</code></pre>
<p>Use a <code>prefix</code> if several applications share the same Valkey instance and need separate key spaces.</p>
<hr />
<h2><strong>Operational Behavior</strong></h2>
<p>Deduplication is a best-effort feature, not a guarantee of exactly-once processing.</p>
<p>Duplicate upstream requests can still occur if the in-flight lock expires before the upstream response is ready, if a gateway instance fails while handling the leader request, if a waiter times out, or if retries run out. In these cases, the gateway just switches back to normal proxying.</p>
<p>The main timing options are:</p>
<ul>
<li><p><code>timeout</code>: how long a duplicate request waits for the leader response before retrying lock acquisition</p>
</li>
<li><p><code>retries</code>: how many additional deduplication attempts are made before falling back to normal proxying</p>
</li>
<li><p><code>ttl</code>: how long stored responses remain available for waiting requests</p>
</li>
<li><p><code>lockTtl</code>: how long an in-flight lock can live before it expires</p>
</li>
</ul>
<p>Defaults are:</p>
<pre><code class="language-json">{
 "timeout": 1000,
 "retries": 3,
 "ttl": 10000,
 "lockTtl": 500
}
</code></pre>
<p>Responses are fully buffered before being replayed. This works well for short bursts of duplicate reads, but large responses can use more gateway memory and, with Valkey, add some storage overhead. It’s best to start with routes where responses are small and where repeated upstream work is already costing you in money, speed, or capacity.</p>
<hr />
<h2><strong>Custom Gateway Handlers</strong></h2>
<p>Deduplication comprises custom gateway handlers. When both a custom handler and deduplication are configured, <code>deduplication</code> runs first, and the leader request is delegated to the handler.</p>
<p>Handlers that use <code>reply.from()</code> do not need special handling. Platformatic Gateway uses <code>reply.from()</code> from <a href="https://github.com/fastify/fastify-reply-from">@fastify/reply-from</a> to proxy upstream requests.</p>
<pre><code class="language-javascript">export function handler(request, reply, dest, options) {
 return reply.from(dest, options)
}
</code></pre>
<p>If a handler overrides <code>onResponse</code> or <code>onError</code>, it can call the helper functions provided in <code>options</code>, so waiting requests still receive the correct signal:</p>
<pre><code class="language-javascript">export function handler(request, reply, dest, options) {
 return reply.from(dest, {
   ...options,
   async onResponse(request, reply, res) {
     reply.header('x-custom-handler', 'true')
     return options.deduplicateResponse(request, reply, res)
   },
   async onError(reply, error) {
     return options.deduplicateError(reply, error)
   }
 })
}
</code></pre>
<p>Handlers that send responses directly without <code>reply.from()</code> cannot be replayed by gateway deduplication.</p>
<hr />
<h2><strong>Metrics</strong></h2>
<p>The feature also adds Gateway metrics so you can prove whether deduplication is helping in production:</p>
<ul>
<li><p><code>gateway_deduplication_leader_count</code></p>
</li>
<li><p><code>gateway_deduplication_waiter_count</code></p>
</li>
<li><p><code>gateway_deduplication_replay_count</code></p>
</li>
<li><p><code>gateway_deduplication_fallback_count</code></p>
</li>
<li><p><code>gateway_deduplication_error_count</code></p>
</li>
</ul>
<p>These counters help answer real-world questions: how many requests became leaders, how many waited, how many were replayed, and how often the gateway had to switch back to normal proxying.</p>
<hr />
<h2><strong>Conclusion</strong></h2>
<p>Gateway deduplication works best when lots of clients request the same resource at once, and the upstream response can be safely reused for matching keys. This is just like the product launch or hot-news example from earlier: many users show up at once, the cache is cold or refreshing, and your app is about to generate the same page over and over.</p>
<p>The best places to start are public, read-heavy routes, framework prefetch endpoints, cache refresh paths, and expensive upstream reads with limited response sizes. Turn it on for a small set of routes first. Keep an eye on the leader, waiter, replay, and fallback metrics. Then, expand to other routes where you see duplicate work causing the most trouble.</p>
<p>You’ll see results right away: the gateway handles traffic spikes, your services do less repeated work, and users get more consistent response times during busy periods.</p>
<p>This kind of optimization adds up over time. You protect your upstream resources without changing your app code. You cut down on unnecessary backend load before it hits your databases, APIs, or rendering services. You also get metrics to see if the feature is delivering value. And if deduplication can’t help in a certain case, the request just goes through as usual.</p>
<p>For teams using Platformatic Gateway in front of modern web apps, especially self-hosted Next.js apps, request deduplication is a practical way to make read-heavy traffic more manageable. It gives you a safety net for traffic bursts, an easier way to scale with Valkey, and a rollout approach that doesn’t require changing your backend services.</p>
]]></content:encoded></item><item><title><![CDATA[AWS ECS auto-scaler is broken
(don’t worry, we’ve fixed it) ]]></title><description><![CDATA[Compare AWS ECS autoscaling with Platformatic ICC and discover how predictive ELU-based scaling improves latency, reliability, and performance.]]></description><link>https://blog.platformatic.dev/aws-ecs-autoscaler-vs-platformatic-icc</link><guid isPermaLink="true">https://blog.platformatic.dev/aws-ecs-autoscaler-vs-platformatic-icc</guid><category><![CDATA[AWS]]></category><category><![CDATA[ECS]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[Cloud Computing]]></category><category><![CDATA[performance]]></category><category><![CDATA[Devops]]></category><category><![CDATA[infrastructure]]></category><dc:creator><![CDATA[Ivan Tymoshenko]]></dc:creator><pubDate>Thu, 04 Jun 2026 16:25:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/f3f4c363-7325-45af-bb97-02dc453a8f5a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you run Node.js services on <a href="https://docs.aws.amazon.com/ecs/">AWS ECS</a>, you don’t have many built-in ways to handle changing loads. Your only two options respond within minutes: <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/target-tracking-scaling-policy-overview.html">Target Tracking Scaling</a> and <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/step-scaling-policy-overview.html">Step Scaling</a>. Both monitor a <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html">CloudWatch</a> metric (usually CPU), compare it to a set threshold, and then add or remove tasks. The scalers will accurately react to changes, but always with a delay of several minutes:</p>
<ul>
<li><p>Target Tracking won’t start scaling up until CPU usage has stayed above the threshold for three minutes in a row, and it won’t scale down until it’s been below for fifteen minutes. (<a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-autoscaling-targettracking.html">These timings are set by AWS and can’t be changed.</a>)</p>
</li>
<li><p>Step Scaling can be set to react after just one minute over the threshold, which is quicker, but it’s still reactive, still based on CPU, and still doesn’t see what’s happening inside the Node.js event loop.</p>
</li>
</ul>
<p>In this article, we’ll dig into the algorithms we’ve designed to achieve more effective auto-scaling responses within our Intelligent Command Center (“ICC”). This tuning can make a massive impact on performance:</p>
<ul>
<li><p>ICC kept the median request time at <strong>20 ms</strong> with a <strong>99.99%</strong> success rate</p>
</li>
<li><p>Step Scaling’s median was 471 ms (about 23 times slower) with a <strong>85.58%</strong> success rate</p>
</li>
<li><p>Target Tracking was even slower, with a <strong>929 ms</strong> median with a <strong>74.76%</strong> success rate</p>
</li>
</ul>
<hr />
<h2><strong>How AWS-native ECS scalers actually work</strong></h2>
<p>ECS doesn’t ship its own autoscaler. It delegates to <strong>Application Auto Scaling (AAS)</strong>, a generic AWS service that scales ECS services, DynamoDB tables, Lambda concurrency, and a dozen other targets. AAS provides four scaling policy types: Target Tracking, Step Scaling, Scheduled Scaling, and Predictive Scaling.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/26d72aba-f6ed-4c79-86ba-f0638eda013f.png" alt="" style="display:block;margin:0 auto" />

<p>Target Tracking and Step Scaling are the two that engage with dynamic load, the ones the average team configures and the ones we benchmark in this post. Scheduled Scaling and Predictive Scaling solve a different problem; we come back to them in a separate section below. The mechanics of all four are worth understanding because they explain why the benchmark results look the way they do.</p>
<h3><strong>Target Tracking Scaling</strong></h3>
<p>Target Tracking is the “easy mode” option. You pick a metric (the predefined <code>ECSServiceAverageCPUUtilization</code> is the most common), set a target value (e.g., 50%), and AAS handles the rest. You never write a CloudWatch alarm yourself.</p>
<p>When you register a Target Tracking policy with a target 50%, AAS quietly creates two CloudWatch alarms:</p>
<ul>
<li><p><strong>AlarmHigh</strong>: <code>CPU &gt; 50%</code> over <strong>3 consecutive 60-second windows</strong> → triggers scale-up</p>
</li>
<li><p><strong>AlarmLow</strong>: <code>CPU &lt; 45%</code> over <strong>15 consecutive 60-second windows</strong> → triggers scale-down</p>
</li>
</ul>
<p><em>(Scale-down fires at 90% of the target metric, i.e. at 45% if your target is 50%. That offset is also hardcoded.)</em></p>
<p>These intervals are <strong>not configurable</strong>. You can change the target value, the cooldowns, and a few other knobs, but the 3-of-3 and 15-of-15 evaluation periods are baked into the AAS implementation. AWS does not document these evaluation periods on the <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/target-tracking-scaling-policy-overview.html">Target Tracking concepts page</a>; you only see them by inspecting the CloudWatch alarms AAS creates after you register a policy. <em>(For comparison, the</em> <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/AutoScaling.html"><em>DynamoDB auto scaling page</em></a> <em>does state its equivalent numbers explicitly: 2 minutes for scale-up, 15 datapoints for scale-down. AWS documents these alarm parameters per-service, when it does so at all.)</em></p>
<p>When the alarm does fire, the scaling decision uses the same formula as Kubernetes HPA:</p>
<pre><code class="language-plaintext">new_desired = ceil(current_tasks × current_cpu / target_cpu)
</code></pre>
<p>So if 4 tasks are running at 90% CPU with a 50% target, AAS sets the desired count to ceil(4 <code>× 90 / 50) = 8</code>. The same one-shot snapshot logic as <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/#algorithm-details">HPA</a>, just with three minutes of mandatory pre-roll added to the front. <em>(You can find more details on how the HPA works and how we’ve improved scaling on Kubernetes with ICC</em> <a href="https://blog.platformatic.dev/ahead-of-time-scaling-platformatic-icc-predictive-autoscaling"><em>here</em></a><em>.)</em></p>
<h3><strong>Step Scaling</strong></h3>
<p>Step Scaling is the “advanced” option. You write your own CloudWatch alarms, with your own thresholds and evaluation periods, and you provide AAS with a <strong>step adjustment table</strong> that maps “how far over the threshold” to “how many tasks to add.” A small breach adds one task; a larger breach adds more. We paired this with a CloudWatch alarm tuned to fire after a single 60-second window rather than three.</p>
<p>Our scale-up configuration:</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/ed396e01-2ac3-4939-b8e7-dd228bcb4fc8.png" alt="" style="display:block;margin:0 auto" />

<p>With a CloudWatch alarm that fires after just <strong>1 evaluation period of 60s</strong> above the 50% threshold, this scales up faster than Target Tracking.</p>
<p>However, we found the graduated step adjustments turn out to be less useful in practice than they look on paper: once a scale-up fires and a task gets added, the next CloudWatch datapoint a minute later often shows CPU back in the lowest band, so the <code>+2</code> and <code>+3</code> jumps fire rarely or not at all. In our run, the scaler fired <code>+1</code> once and <code>+2</code> once, never <code>+3</code>. The peak observed cluster was 7 desired / 9 running (the extra running tasks were ECS replacing saturated ones, not scaling), despite the policy allowing much faster expansion if the CPU had stayed sufficiently elevated.</p>
<p>There’s also a tradeoff with the advanced approach: you have to manage the alarms, thresholds, and step adjustments yourself, and keep them consistent across services. AAS Target Tracking handles this automatically. Step Scaling gives you faster reactions, but you have more settings to maintain, and in the worst cases, it only works a bit better than Target Tracking once the alarms go off.</p>
<h3><strong>What about AWS Predictive Scaling?</strong></h3>
<p>AAS supports two other policy types: Scheduled Scaling and <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/aas-create-predictive-scaling-policy.html">Predictive Scaling</a>.</p>
<p>Scheduled Scaling is exactly what it sounds like, “scale to N tasks at 9:00 every weekday”, and it has the obvious limitation that it can’t react to anything not on the schedule.</p>
<p>Predictive Scaling is the more interesting one, because it also calls itself “predictive,” and a careful reader should be asking how it relates to what ICC does.</p>
<p>Predictive Scaling uses machine learning to detect cyclical patterns in your historical CloudWatch metrics, typically daily and weekly cycles. It requires a minimum of <strong>14 days of history</strong> to produce useful forecasts, looks <strong>up to 48 hours ahead</strong>, and revises the forecast <strong>once an hour</strong>. A configurable <code>SchedulingBufferTime</code> <em>(up to 1 hour, default 5 minutes)</em> tells AWS how early to start pre-warming capacity ahead of the forecasted load. It is designed to be used <em>alongside</em> Target Tracking, not as a replacement: Predictive Scaling handles the cyclical baseline, Target Tracking handles deviations.</p>
<p>Both AWS Predictive Scaling and ICC’s predictive scaling are forecast-based, but they operate on completely different timescales and solve different problems:</p>
<ul>
<li><p><strong>AWS Predictive Scaling</strong> asks, “What does this Tuesday morning usually look like?” It forecasts at the scale of <strong>hours and days</strong>, needs a <strong>historical pattern</strong> to detect, and refreshes its plan <strong>once an hour</strong>.</p>
</li>
<li><p><strong>ICC’s predictive scaling</strong> asks, “What is ELU about to do in the next 35 seconds?” It forecasts at the scale of <strong>seconds</strong>, needs a <strong>live trend</strong> in the current signal, and refreshes its decision <strong>every 10 seconds</strong>.</p>
</li>
</ul>
<p>In the benchmark in this post, a single 7-minute traffic ramp on a freshly deployed service, AWS Predictive Scaling would do nothing at all. There is no 14-day history to train from, no cyclical pattern to detect, and even if both were present, the hourly forecast cadence is far too coarse for a 2-minute ramp.</p>
<p>Real production traffic doesn’t follow a perfect pattern. A flash sale, a viral post, a partner deployment that doubles your API load, or an upstream outage that triples your support traffic, none of these show up in last week’s data.</p>
<p>The benchmark in this post focuses on the AWS scalers that actually engage when load changes within minutes, because for a Node.js application past the latency cliff <em>(i.e., past the point of event loop saturation)</em>, that is the only timescale that matters.</p>
<h3><strong>The structural problems with reactive scaling on ECS</strong></h3>
<p>Even if you choose the best AWS-native option and set it up as aggressively as possible, the reactive approach has built-in problems that no configuration can fix.</p>
<p><strong>The startup gap.</strong> Once a reactive scaler decides to add tasks, there is a delay before those tasks actually serve traffic:</p>
<ol>
<li><p>The CloudWatch alarm evaluates and changes state (60s minimum for Step, 180s for Target Tracking).</p>
</li>
<li><p>AAS receives the alarm transition and applies the scaling policy.</p>
</li>
<li><p>ECS places the task on an EC2 instance with available capacity.</p>
</li>
<li><p>The container image is pulled <em>(or skipped if cached on the host)</em>.</p>
</li>
<li><p>The container starts, and the application initializes.</p>
</li>
<li><p>The ECS health check passes.</p>
</li>
<li><p>The ALB registers the task in the target group and begins routing traffic.</p>
</li>
</ol>
<p>In our benchmark, we pre-cached the app image on every EC2 host during deployment, so we skipped step 4. With everything else tuned, it took about 30 to 60 seconds from when the alarm fired to when the task started serving traffic. Without this, it usually takes two to four minutes. Either way, this delay adds to the alarm evaluation time, which is the main source of lag.</p>
<p>If your ECS service runs on EC2 and the underlying Auto Scaling Group needs to add an instance to fit the new task, add another two to five minutes for EC2 boot, ECS agent registration, and the ASG/Capacity Provider machinery. We sized our cluster to avoid this in the benchmark, but it’s the common case in production.</p>
<p><strong>The CloudWatch pipeline lag.</strong> Even if you’re not on the AWS-native scalers, CloudWatch itself introduces a delay. Standard metrics aggregate over 60-second windows and arrive with roughly 30 seconds of ingestion lag. If you push a custom ELU metric via PutMetricData, you’ve already added 60 to 90 seconds of staleness before any alarm can evaluate it. There is no version of “fast” that goes through CloudWatch.</p>
<p><strong>The saturation cap.</strong> When the metric has a natural ceiling, like ELU at 1.0 or CPU at 100%, the scaler loses visibility into the actual load. A task at 100% CPU might need one more task or ten more, but the formula sees the same number either way. This forces the scaler into a staircase pattern: add tasks based on what it can see, wait for the new tasks to also saturate, and only then realize more are needed. Each step requires a full cycle of task startup and saturation before the next decision can be made.</p>
<p><strong>The redistribution problem.</strong> Every time AAS adds a task, it creates a temporary distortion in the metric. The new task starts receiving traffic immediately, but the existing tasks don’t shed their load at the same pace: queues take time to drain, in-flight requests must complete, and garbage collection needs to settle. During this transition, the new task’s CPU is rising while the old tasks’ CPU hasn’t dropped yet. The scaler sees the sum go up and interprets it as growing demand, when it’s actually the overlap of old and new tasks, both holding load at the same time. This can lead AAS to add tasks that aren’t needed, then scale them back fifteen minutes later.</p>
<p>All these issues have the same root cause: each scaling decision is made in isolation. The scaler doesn’t remember past values, can’t see trends, and can’t account for the delay between making a decision and when new capacity is actually available.</p>
<hr />
<h2><strong>Platformatic Intelligent Command Center on ECS</strong></h2>
<p><a href="https://icc.platformatic.dev/">Platformatic Intelligent Command Center (ICC)</a> is the control plane for managing, monitoring, and optimizing Node.js applications running on Watt. A single Watt instance can host multiple Node.js applications, each in its own worker thread within the same process. In an ECS deployment, each task runs one Watt instance, which may host one or several applications as worker threads.</p>
<p>A companion module, <a href="https://github.com/platformatic/watt-extra">@platformatic/watt-extra</a>, runs Watt in each task. It collects runtime metrics, including per-application ELU and heap usage, and streams them to ICC.</p>
<p>The ECS integration differs from the Kubernetes one in exactly one place: how ICC applies its scaling decisions. On Kubernetes, ICC updates the <code>replicas</code> field on a Deployment object. On ECS, ICC calls the <a href="https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html">UpdateService</a> API directly to change <code>desiredCount</code>. Everything between the metric and the decision is identical: the same metric collection, the same prediction algorithm, the same scale-up logic.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/cdb3e010-9486-4bd7-ab69-b2d47706f980.png" alt="" style="display:block;margin:0 auto" />

<p>Importantly, ICC skip<strong>s CloudWatch completely</strong>. Watt-Extra sends raw ELU samples straight to ICC, which runs its algorithm and calls the ECS API directly. There’s no CloudWatch metric, no alarm, no 60-second aggregation, and no 3-of-3 evaluation period. <strong>This one design choice removes over three minutes of built-in delay before the algorithm even starts.</strong></p>
<hr />
<h2><strong>How ICC’s predictive scaling works</strong></h2>
<p>A reactive scaler asks: “Is the application overloaded right now?” and acts on the answer. By the time new tasks are ready, the answer has changed, usually for the worse.</p>
<p>Instead, ICC tracks the load trend over time: not just the current value, but whether it is rising, falling, or stable, and how fast. It extrapolates the trend forward by the time it takes a new task to start and begin serving traffic. If the projected load exceeds the capacity of the current task count, ICC adds tasks immediately. The full details of the algorithm are described in the <a href="https://arxiv.org/abs/2604.19705">algorithm whitepaper</a>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/a1269bb2-59a1-4d26-bdb2-bccbcb18b1a4.png" alt="" style="display:block;margin:0 auto" />

<p>The chart shows ELU per task over the last 20 seconds. The solid line (<em><strong>M_t)</strong></em> has been rising steadily. Right now it’s at 0.73 (\(M_\text{now}\)), just below the 0.75 threshold (dashed red line). ICC sees the trend and projects that by the time a new task would be ready (the prediction horizon $H$), the metric will reach 0.78 (\(M_H\)), above the threshold. So it scales up now, before the overload begins.</p>
<p>The rest of this section explains how the algorithm builds that prediction.</p>
<h3><strong>Aggregate, predict, project</strong></h3>
<p>The algorithm takes per-task metric values (like ELU on each task), combines them into a single cluster-wide number, predicts where that number is heading, and converts the prediction back into a per-task value to compare against the threshold. This <strong>aggregate-predict-project</strong> flow is the backbone of the algorithm.</p>
<p>Why predict on an aggregate? Per-task metrics change for two reasons: external traffic changes and the scaler’s own actions. When the scaler adds a task, the ALB starts routing traffic to it, and ELU on the existing tasks drops, even though external traffic hasn’t changed at all. If the algorithm predicted the trend from per-task ELU, it would see this drop as “load is decreasing” and might delay further scaling when it’s actually needed. The algorithm avoids this by summing ELU across all tasks into a cluster-wide aggregate. When a task is added and the load redistributes, individual ELU values shift, but the total stays approximately the same. The aggregate reflects external traffic changes without being distorted by scaling actions.</p>
<h3><strong>Cleaning the data</strong></h3>
<p>Raw metric data is not ready for prediction. Tasks send measurements in batches at different times, so at any given moment, some tasks have reported recent data and others haven’t. After a scale-up, new tasks create temporary distortions in the aggregate. Three preprocessing stages handle this before the data reaches the prediction stage.</p>
<ul>
<li><p><strong>Alignment</strong> places irregularly-timed samples onto a uniform time grid (e.g., one tick per second) by interpolation, so values from different tasks can be compared at the same points in time.</p>
</li>
<li><p><strong>Imputation</strong> estimates values for tasks that haven’t been reported yet. At each tick, the algorithm takes the previous total, subtracts the previous values of tasks that have now reported new data, and uses the remainder as the estimated contribution of the tasks still missing. When a late batch arrives, the estimates are replaced by real data and the totals are recomputed.</p>
</li>
</ul>
<p><strong>Redistribution</strong> smooths out the metric distortion after a scale-up. New tasks’ values are included gradually (their contribution ramps from zero to full over a stabilization period) rather than appearing all at once. At the same time, the artificial drop on existing tasks as they shed load is absorbed: the algorithm allows the aggregate to rise (to catch real traffic increases) but prevents it from dropping while new tasks are still stabilizing. Redistribution artifacts are filtered out, but real load changes pass through immediately.</p>
<h3><strong>Predicting the trend</strong></h3>
<p>The cleaned aggregate enters the prediction stage, which uses <a href="https://doi.org/10.1016/j.ijforecast.2003.09.015">Holt’s double exponential smoothing</a>. This method maintains two values at each tick: the <strong>level</strong> (a smoothed estimate of where the aggregate is now) and the <strong>trend</strong> (how fast the aggregate is changing). Each new data point updates both. The level tracks the signal while filtering single-tick noise. The trend builds gradually over multiple ticks, converging to the actual rate of change. This lets the smoothing be aggressive enough to filter noise while still reacting quickly to sustained changes.</p>
<h3><strong>Asymmetric reaction</strong></h3>
<p>The algorithm uses different smoothing for increases and decreases. If the metric rises faster than expected, it reacts quickly, since missing a spike can push the app into the latency cliff before the scaler can help. If the metric drops, it responds more slowly, letting the downward trend build before scaling down. A short dip might just be noise, and scaling down too soon could mean scaling right back up. This matches reality: under-provisioning hurts right away, but a little extra capacity just costs resources.</p>
<h3><strong>The prediction horizon</strong></h3>
<p>The horizon <em><strong>H</strong></em> determines how far into the future the algorithm looks when extrapolating the trend. It is derived from observed task startup times: how long it actually takes a new task to be scheduled, the container to start, the health check to pass, and the ALB to begin routing traffic. ICC measures this from real-scale-up events in the cluster and adapts over time, so the horizon tracks actual infrastructure conditions.</p>
<p>On ECS, our benchmark uses a horizon of 35 seconds, reflecting the typical task startup time we observed with a pre-cached image. ICC continuously measures real startup time as a rolling window of the last five scale-up events and lifts the horizon as needed, so the horizon tracks actual infrastructure conditions rather than relying on a hardcoded constant. A configurable floor and ceiling prevent the horizon from becoming too short (which would reduce the algorithm’s effectiveness) or too long (which would make the extrapolation unreliable).</p>
<p>The decision loop itself runs every 10 seconds (<code>PLT_SIGNALS_SCALER_PROCESSING_COOLDOWN_MS=10000</code>) — slower than the 5-second metric batch arrival under load, so the algorithm has multiple fresh samples to work with on every decision.</p>
<h3><strong>Handling metric saturation</strong></h3>
<p>Some metrics have a natural cap. ELU maxes out at 1.0: once the event loop is fully saturated, ELU cannot rise further, no matter how much more traffic arrives. Without special handling, the trend would decay to zero during saturation, and the algorithm would stop scaling even though the load is still growing behind the cap. ICC handles this by preserving the trend during saturation: the trend is allowed to increase but never decrease while the metric is clipped, so the algorithm continues to scale up even when the signal is flat at its maximum.</p>
<h3><strong>The scaling decision</strong></h3>
<p>The prediction stage produces a predicted aggregate (\(A_H\)): the forecasted total load at the horizon. The decision stage converts this back into a per-task value by dividing by the current task count, producing the projected per-task metric at the horizon (\(M_H\)). If \(M_H\) exceeds the threshold \(\tau\), the algorithm computes how many tasks are needed to keep the per-task metric below the threshold and scales up immediately. If the trend is flat or falling and the metric is within the threshold, it considers scaling down, with a safety margin to avoid immediately scaling right back up.</p>
<p>The full algorithm, including the mathematical formulation and worked examples, is in the <a href="https://arxiv.org/abs/2604.19705">algorithm whitepaper</a>.</p>
<h3><strong>Signals</strong></h3>
<p>Accurate forecasting needs good data. If you average metrics over 15 or 60 seconds, you lose the details that matter for short-term prediction. For example, a sharp spike in the last 5 seconds looks just like a slow climb over 60 seconds. This makes the trend and the forecast less precise.</p>
<p>ICC works with raw metric samples instead. Each task pushes every individual measurement to ICC in batches, with no client-side averaging and no data loss. The batch timing is dynamic: under load, batches are sent frequently (every 5 seconds) to give the scaler fresh data when it matters most. When the application is idle, batches are sent infrequently (every 40 seconds) to save resources. A spike that started 5 seconds ago is visible immediately, not hidden inside a 60-second average that arrives 90 seconds late.</p>
<hr />
<h2><strong>Benchmarks</strong></h2>
<p>To measure what predictive scaling actually buys you on ECS, we ran ICC against Target Tracking and Step Scaling under identical conditions on the same cluster with the same application.</p>
<h3><strong>Test setup</strong></h3>
<p><strong>Application.</strong> A Next.js 16 e-commerce application (App Router, Server Components, SSR) runs on Platformatic Watt with one worker per task. We use the same <a href="https://github.com/platformatic/next-bench">next-bench</a> application from our prior Kubernetes benchmarks, with the same mix of request types (homepage, search, product detail, cart) at the same weights. Each task is sized at 1 vCPU (1024 CPU units) and 2 GiB of memory.</p>
<p><strong>Cluster.</strong> ECS-on-EC2 running on five <code>m7i.xlarge</code> instances (4 vCPU / 16 GiB each, 20 vCPU / 80 GiB total) in <code>us-east-1</code>. The Auto Scaling Group is locked at <code>min=max=desired=5</code>, so the EC2 layer doesn’t add its own scaling lag mid-benchmark. The 20 vCPU cluster capacity is sized to fit the full task ceiling (20 tasks × 1 vCPU) with headroom, so no run is constrained by infrastructure. <strong>Image pre-caching.</strong> The application image is pre-pulled to every EC2 host at deployment time, eliminating ECR pull latency on task start. This is a real-world optimization any production team can do, and it benefits the AWS-native scalers more than it benefits ICC (since AAS sees its 3-minute alarm delay regardless). <strong>Traffic redistribution.</strong> An Application Load Balancer with a <strong>30-second slow start</strong> on the target group (newly-healthy tasks ramp traffic linearly over 30 s rather than getting full round-robin share instantly) and a <strong>10-second deregistration delay</strong> on task shutdown. The slow start prevents V8 JIT compilation on cold code paths from skewing the comparison; the short deregistration delay keeps the picture clean during scale-down events.</p>
<p><strong>Scalers.</strong> All three operate on the same service definition (min 4, max 20 tasks):</p>
<ul>
<li><p><strong>ICC</strong>: predictive scaling on average ELU with a 0.7 threshold</p>
</li>
<li><p><strong>ECS Step Scaling</strong>: CPU utilization with a 50% threshold (1-of-1 × 60s alarm, +1/+2/+3 graduated step adjustments)</p>
</li>
<li><p><strong>ECS Target Tracking</strong>: predefined <code>ECSServiceAverageCPUUtilization</code> metric with a 50% target</p>
</li>
</ul>
<p>ICC scales on ELU because that is the metric that actually tracks Node.js application load. The AWS-native scalers cannot scale on ELU without a custom CloudWatch pipeline, so they scale on CPU at the equivalent threshold. This reflects how each scaler is realistically deployed in production.</p>
<p><strong>Load generator.</strong> <a href="https://k6.io/">Grafana k6</a> running on a dedicated <code>t3.medium</code> EC2 instance in the same VPC, using a <code>ramping-arrival-rate</code> executor (fixed RPS target regardless of server response time) with <code>noConnectionReuse: true</code> to ensure each request requires a fresh TCP and TLS handshake, preventing artificially low latency from connection pooling. The client-side timeout is set to 10 seconds; any request that exceeds it is counted as an error.</p>
<p><strong>Traffic profile.</strong> A single ramp scenario:</p>
<ul>
<li><p>10 seconds at 100 req/s (baseline)</p>
</li>
<li><p>120 seconds linear ramp from 100 to 800 req/s</p>
</li>
<li><p>300 seconds sustained at 800 req/s</p>
</li>
</ul>
<p>This is a common real-world pattern: traffic grows over a couple of minutes as users arrive, then holds at the new level. The total test duration is 7 minutes and 10 seconds. We did not benchmark a sudden zero-to-peak spike on ECS: it tells you almost nothing about scaler quality on infrastructure with multi-minute task startup, because no scaler can fix it.</p>
<h3><strong>Results</strong></h3>
<p>All three scalers responded. ICC acted well before the latency cliff, while Step Scaling and Target Tracking only kicked in after the problem started. The latencies below show the results:</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/6a5610d4-0552-49b2-b6db-e66155d31999.png" alt="" style="display:block;margin:0 auto" />

<p>ICC kept the median request time at <strong>20 ms</strong> with a <strong>99.99%</strong> success rate. Step Scaling’s median was 471 ms—about 23 times slower—and it lost roughly one out of every <strong>seven</strong> requests. Target Tracking was even slower, with a <strong>929 ms</strong> median and <strong>one in four</strong> requests dropped.</p>
<p>Each chart below plots how the cluster behaved over time during one scaler’s run: the average ELU across all tasks (purple), the task count (black step line), and the target request rate (blue shaded area). The dashed red line marks the ELU threshold of 0.7. For Step Scaling and Target Tracking, we also overlay CloudWatch CPU (orange) — the metric they actually scale on.</p>
<p><strong>ICC.</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/499c70aa-e8a2-4244-aad0-3a3d822b3f52.png" alt="" style="display:block;margin:0 auto" />

<p>The first scale-up happens before ELU crosses the threshold. This shows the predictive part in action: ICC looks about 35 seconds ahead and acts based on the forecast, not just the current value. When peak load arrives, the cluster already has 9 tasks running, added before the demand hits, not after overload.</p>
<p><strong>ECS Step Scaling.</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/bd644abb-2291-4898-9633-9c7046a76d1a.png" alt="" style="display:block;margin:0 auto" />

<p>Step Scaling has the same reactive weaknesses we discussed earlier: it only acts after a threshold is crossed, scales in fixed steps instead of matching demand, and uses CPU instead of ELU. On Kubernetes, these differences set ICC apart from reactive scalers. On ECS, though, the main issue is the built-in delay in AWS’s alarm system. Even the best-tuned Step Scaling alarm can’t fire in less than two to three minutes. By the time the first scale-up happens, the app has already been overloaded for almost four minutes.</p>
<p><strong>ECS Target Tracking.</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/22c88e66-2e8d-452d-9cf3-c49f57ebb41e.png" alt="" style="display:block;margin:0 auto" />

<p>Target Tracking has the same reactive weaknesses, plus an even longer alarm delay—the hardcoded 3-of-3 × 60s rule means the delay exceeds the entire 7:10 test. The app stays overloaded the entire time, and the only scale-up happens just two seconds before the test ends.</p>
<hr />
<h2><strong>Why does the alarm take so long to fire?</strong></h2>
<p>The multi-minute delays are the result of how CloudWatch alarm evaluation is structured. Every CloudWatch alarm runs on three parameters:</p>
<ul>
<li><p><strong>Period</strong>: how long CloudWatch aggregates raw data into a single data point. For ECS service CPU metrics, this is 60 seconds.</p>
</li>
<li><p><strong>Evaluation Periods</strong>: how many recent data points the alarm looks at when deciding whether to change state.</p>
</li>
<li><p><strong>Datapoints to Alarm</strong>: how many of those data points must breach the threshold to trigger ALARM</p>
</li>
</ul>
<p>But the alarm doesn’t read these data points directly from your service. Three separate delays stack up before it can transition:</p>
<ol>
<li><p><strong>Metric reporting lag.</strong> ECS reports CPU in 1-minute periods. A data point for the window 12:00–12:01 doesn’t appear in CloudWatch the instant 12:01 arrives; there’s roughly a minute of pipeline lag before it becomes available for the alarm to read. AWS does not document this latency precisely, and it varies by service.</p>
</li>
<li><p><strong>Alarm evaluation frequency.</strong> CloudWatch alarms with a Period of 60 seconds or longer <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/alarm-evaluation.html">evaluate once per minute</a>. Even if a data point becomes available between ticks, the alarm won’t act on it until the next evaluation cycle.</p>
</li>
<li><p><strong>The evaluation window itself.</strong> For 1-of-1, the window is 60 seconds — one period must breach. For 3-of-3, three consecutive periods must breach. That’s 3 minutes of sustained breach data, just to satisfy the alarm condition.</p>
</li>
</ol>
<p>These three stack. An <a href="https://repost.aws/articles/ARtfXuUalKQLycBz2IfuVavQ/understanding-cloudwatch-alarm-evaluation-why-alarms-delay-fire-unexpectedly-or-get-stuck">AWS re:Post article on alarm-evaluation timing</a> walks through an example timeline for a 3-of-3 × 1-min alarm: roughly 4 minutes from “metric first breaches the threshold” to “alarm fires.”</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/9c3cebe9-46c3-44cf-b573-8de181617fbc.png" alt="" style="display:block;margin:0 auto" />

<p>The diagram traces each scaler on the same time axis, one lane each.</p>
<p>ICC’s lane is dense with green ticks, one decision-loop evaluation every 10 seconds. The first scale-up fires at T+1:24, before a 1-minute CloudWatch period would even have a complete data point to evaluate.</p>
<p>Step Scaling spends the first minute filling one over-threshold period, then sits in the orange band, the reporting, alarm-evaluation, and AAS-handoff stack listed above. First scale-up lands at T+5:20.</p>
<p>Target Tracking goes through the same orange band, but its yellow band runs three full minutes first, the hardcoded 3-of-3 requirement, before the orange pipeline even begins. First scale-up lands at T+7:08.</p>
<p>Using high-resolution custom metrics or shorter evaluation windows can help a bit, but every CloudWatch-based scaler on ECS still works on a minute-by-minute basis.</p>
<hr />
<h2><strong>Conclusion</strong></h2>
<p>Predictive scaling with ICC removes the built-in delays associated with standard methods of scaling ECS reading ELU straight from each task to predict where load is going, and scaling before demand hits.</p>
<p>In our benchmark, <strong>ICC had a 99.99% success rate and 20 ms median latency</strong>, while Step Scaling lost 14% of requests and Target Tracking lost 25%, with both hitting the 10-second client timeout for the slowest requests.</p>
<p>If you’re running high-traffic Node.js on ECS and want to talk through how this would fit your workload, drop us a note at <a href="mailto:hello@platformatic.dev">hello@platformatic.dev</a> or reach out on LinkedIn.</p>
<p>Thanks for reading, and happy building.</p>
]]></content:encoded></item><item><title><![CDATA[Destino: Doom in Your Terminal, Powered by Node.js FFI]]></title><description><![CDATA[Destino runs Doom inside the terminal using Node.js FFI, DoomGeneric, & OpenTUI. JavaScript and native code work together for real-time rendering.]]></description><link>https://blog.platformatic.dev/destino-doom-terminal-nodejs-ffi</link><guid isPermaLink="true">https://blog.platformatic.dev/destino-doom-terminal-nodejs-ffi</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[terminal]]></category><dc:creator><![CDATA[Paolo Insogna]]></dc:creator><pubDate>Tue, 19 May 2026 14:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/64ee1da6-90f3-4206-9858-c5c23bfa09b0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://github.com/platformatic/destino">Destino</a> lets you play Doom right in your terminal using Node.js.</p>
<p>It might sound like a joke, and that’s how it began. At the <a href="https://nodejs.org/en/blog/events/collab-summit-2026-london">Node Collaborator Summit in London</a>, Paolo made the classic DOOM comment. Matteo and Luca decided to run with it, turning the joke into a real project. The name was an easy choice: in Italian, “destino” means “doom”.</p>
<p>Destino brings together <a href="https://nodejs.org/api/ffi.html">node:ffi</a>, <a href="https://github.com/ozkl/doomgeneric">doomgeneric</a>, and <a href="https://github.com/sst/opentui">OpenTUI</a>. JavaScript controls the main loop, while the Doom engine runs natively. OpenTUI handles turning the framebuffer into terminal graphics, and sound is managed by DoomGeneric’s SDL2 audio backend. You can also package everything as a Node.js Single Executable Application (SEA), bundling the JavaScript, native libraries, WAD, and sound font.</p>
<hr />
<h2><strong>Why build this?</strong></h2>
<p>First, because it’s funny. Seeing Doom run at 35 fps in a terminal, with sound, powered by Node.js FFI, is the kind of thing that grabs people’s attention.</p>
<p>But what’s the real point we were trying to prove here?</p>
<p>For a long time, calling native code from Node.js meant writing a native addon, spawning a subprocess, using WebAssembly, or putting the native code behind a service. These options still work, but they add serious complexity and overhead, changing how you build, package, deploy, or debug your program.</p>
<p>FFI offers Node.js another way: you load a native library, describe the ABI, and call it straight from JavaScript.</p>
<p>Doom is a great way to test this idea. It needs a steady game loop, keyboard input, native memory, framebuffer access, assets, audio, and proper cleanup so your terminal isn’t left in a bad state. If Node.js can handle all that, FFI becomes much more concrete.</p>
<p>And yes, if Node.js can run Doom like this, it can probably call the C library buried in your enterprise stack too.</p>
<hr />
<h2><strong>The shape of the program</strong></h2>
<p>Destino uses <a href="https://github.com/ozkl/doomgeneric">doomgeneric</a> as the engine. The project builds it as a native shared library with a small C platform layer. That layer exposes only what JavaScript needs:</p>
<ul>
<li><p>Initialize Doom with a WAD file and sound font</p>
</li>
<li><p>Advance the engine one tick</p>
</li>
<li><p>Send key press and release events</p>
</li>
<li><p>Return the framebuffer pointer</p>
</li>
<li><p>Report when a frame is ready</p>
</li>
<li><p>Clean up native resources</p>
</li>
</ul>
<p>Node.js loads the shared library with <code>node:ffi</code>:</p>
<pre><code class="language-javascript">const {
 lib,
 functions: {
   init,
   doomgeneric_Tick: tick,
   send_key: sendKey,
   get_framebuffer: getFramebuffer,
   frame_ready: frameReady,
   clear_frame_ready: clearFrameReady,
   cleanup
 }
} = dlopen(libPath, {
 init: { parameters: ['int32', 'pointer', 'string', 'pointer'], result: 'pointer' },
 send_key: { parameters: ['uint8', 'int32'], result: 'void' },
 get_framebuffer: { parameters: [], result: 'pointer' },
 frame_ready: { parameters: [], result: 'int32' },
 clear_frame_ready: { parameters: [], result: 'void' },
 cleanup: { parameters: [], result: 'void' },
 doomgeneric_Tick: { parameters: [], result: 'void' }
})
</code></pre>
<p>There’s no generated binding layer in the repository, and no native addon just to expose a few functions. The native library stays native, and the integration is done with plain JavaScript.</p>
<p>The main loop is intentionally simple, which is exactly what you want:</p>
<pre><code class="language-javascript">runtime.timer = setInterval(() =&gt; {
 runtime.engine.tick()

 if (!runtime.engine.frameReady()) {
   return
 }

 runtime.renderer.render()
 runtime.engine.clearFrameReady()
}, 1000 / 35)
</code></pre>
<p>Doom runs at 35 Hz. JavaScript calls tick(), checks if a frame is ready, renders it, and then clears the flag.</p>
<p>The frame path is pull-based. The C side doesn’t call back into JavaScript for every frame. Instead, JavaScript asks for work when it’s ready. This keeps the control flow simple and the JS/native boundary going in one direction for the main loop.</p>
<hr />
<h2><strong>The FFI boundary</strong></h2>
<p>The best part about <code>node:ffi</code> isn’t just that JavaScript can call C. It’s that the boundary is visible in your code. You can see the native symbols, parameter types, and return types right where the library is loaded.</p>
<p>That’s powerful, but it’s not magic. FFI is low-level. If you mess up a pointer’s lifetime, pass the wrong type, or get a function signature wrong, you might crash instead of getting a friendly JavaScript error. That’s why Destino keeps the surface area small.</p>
<p>The performance side is getting interesting, too. In the Banter episode, we talked about early <code>node:ffi</code> calls taking around 150 nanoseconds. Recent work has brought that down to roughly 15 nanoseconds per call, close to the theoretical minimum for this kind of boundary.</p>
<p>Destino doesn’t need ultra-low call overhead to be a fun demo. A 35 Hz game loop isn’t high-frequency trading. Still, performance matters. It shows that FFI doesn’t have to be limited to rare setup calls. With a careful API, it can be used in real runtime paths.</p>
<hr />
<h2><strong>Rendering Doom in a terminal</strong></h2>
<p>The Doom engine exposes a BGRA framebuffer. Destino maps that native memory into a JavaScript <code>Buffer</code> through <code>node:ffi</code>, scales it, and passes the result to OpenTUI.</p>
<p>The key thing is that Destino doesn’t copy the native framebuffer just to look at it. It borrows the native memory and reuses a separate scaled output buffer for rendering.</p>
<p>OpenTUI consumes a 2x2 supersample pixel grid per terminal cell, so Destino scales the frame into that shape while preserving Doom’s aspect ratio. It also handles the usual terminal details: alternate screen mode, hidden cursor, centring, margins, and cleanup.</p>
<p>There is also a Kitty graphics path. Destino uses it only when the terminal has fewer than 100 rows, and the terminal supports the Kitty graphics protocol, such as Kitty, Ghostty, or WezTerm. In that mode, Destino converts frames to RGBA, chunks them into protocol payloads, writes them to the terminal, and deletes the previous image after the new one is drawn.</p>
<p>Terminals aren’t game consoles. They have cell geometry, escape sequences, scrollback, inconsistent protocol support, and lots of odd behavior across emulators. Destino uses only what it needs and keeps the renderer code separate from the engine.</p>
<p><a class="embed-card" href="https://youtu.be/AtKZjMPAU2A">https://youtu.be/AtKZjMPAU2A</a></p>

<hr />
<h2><strong>Input is the awkward part</strong></h2>
<p>Doom needs key press and release events, but terminals are much better at handling text than acting as game controllers.</p>
<p>Destino uses the <a href="https://sw.kovidgoyal.net/kitty/keyboard-protocol/">Kitty keyboard protocol</a> when available because it can report press, repeat, and release events. The input parser maps those terminal events to Doom key codes. Keybindings live in <code>destino.json</code>, so they are easy to change.</p>
<p>The defaults are what you would expect:</p>
<table style="width:508px"><colgroup><col style="width:342px"></col><col style="width:166px"></col></colgroup><tbody><tr><td><p>Action</p></td><td><p>Keys</p></td></tr><tr><td><p>Move forward</p></td><td><p><code>w</code>, <code>up</code></p></td></tr><tr><td><p>Move backward</p></td><td><p><code>s</code>, <code>down</code></p></td></tr><tr><td><p>Turn left</p></td><td><p><code>a</code>, <code>left</code></p></td></tr><tr><td><p>Turn right</p></td><td><p><code>d</code>, <code>right</code></p></td></tr><tr><td><p>Strafe left</p></td><td><p>q, <code>,</code></p></td></tr><tr><td><p>Strafe right</p></td><td><p><code>e</code>, <code>.</code></p></td></tr><tr><td><p>Fire</p></td><td><p><code>space</code>, <code>ctrl</code></p></td></tr><tr><td><p>Use</p></td><td><p><code>enter</code></p></td></tr><tr><td><p>Menu</p></td><td><p><code>escape</code></p></td></tr><tr><td><p>Pause</p></td><td><p><code>p</code></p></td></tr></tbody></table>

<p>On first run, Destino writes <code>destino.json</code> in the current directory and exits. It tries to find <code>freedoom1.wad</code> and <code>.sf2</code> files under the current directory, writes the paths it finds, and leaves you with a config file to review before starting the game.</p>
<p>It’s a small quality-of-life detail, but it matters. The first run shouldn’t feel like a scavenger hunt through command-line flags.</p>
<hr />
<h2><strong>Audio stays native</strong></h2>
<p>Destino does not mix audio in JavaScript. DoomGeneric handles sound through SDL2 and SDL2_mixer. Node.js coordinates the process, but the native audio path does the audio work.</p>
<p>That split is what makes the project work well. JavaScript takes care of orchestration, configuration, input, rendering choices, packaging, and process lifecycle. The native code handles the engine and audio.</p>
<p>Neither side has to pretend to be something it’s not.</p>
<hr />
<h2><strong>Packaging it</strong></h2>
<p>Destino can be packaged as a Node.js Single Executable Application (SEA) on macOS and Linux:</p>
<pre><code class="language-plaintext">npm install
npm run dependencies
npm run build
npm run sea
</code></pre>
<p>The SEA build bundles the JavaScript entry point, native libraries, WAD files, and SF2 sound font into <code>dist/destino</code>. It also enables <code>--experimental-ffi</code>, so the result can run directly:</p>
<pre><code class="language-plaintext">./dist/destino
</code></pre>
<p>For a demo like this, SEA takes care of a lot of the setup. The executable can include the JS bundle, Doom library, renderer, assets, and sound font all together.</p>
<p>There is one practical detail: the native libraries and game assets still need filesystem paths at runtime. Destino embeds them as SEA assets, then extracts them on startup into a per-process temporary directory such as <code>destino-${process.pid}</code>. The runtime uses <code>node:sea</code>’s <code>getAssetKeys()</code> and <code>getRawAsset()</code> APIs to enumerate the embedded assets, recreate their directory structure, and write them to disk before loading the Doom and OpenTUI libraries. On shutdown, it removes the temporary directory.</p>
<p>The extraction code is small, but it’s the kind of thing other SEA apps will probably need too. If more projects start bundling native libraries and assets inside SEA binaries, this could become a reusable helper instead of something everyone copies by hand.</p>
<p>Native packaging is still where platform details come into play. Shared library names, linker behavior, system packages, and asset paths all matter.</p>
<hr />
<h2><strong>Trying it</strong></h2>
<p>Destino needs Node.js 26.1.0, the first Node.js release with <code>node:ffi</code> support.</p>
<p>You also need <code>cmake</code>, <code>clang</code>, <code>pkg-config,</code> <code>unzip</code>, <code>SDL2_mixer</code> development files, a Doom-compatible WAD such as Freedoom, an SF2 sound font such as GeneralUser GS, and a terminal with Kitty keyboard protocol support.</p>
<p>Automatic dependency setup is supported on macOS and Ubuntu Linux:</p>
<pre><code class="language-plaintext">npm install
npm run dependencies
npm run build
</code></pre>
<p>Then run it with Node.js 26.1.0:</p>
<pre><code class="language-plaintext">/path/to/node --experimental-ffi src/index.js
</code></pre>
<p>On the first run writes <code>destino.json</code> and exits. Check the generated paths, then run the same command again.</p>
<p>If your terminal has fewer than 100 rows and supports Kitty graphics, Destino uses the Kitty renderer. Otherwise, resize the terminal to at least 160 columns by 100 rows.</p>
<hr />
<h2><strong>The enterprise point hiding in the joke</strong></h2>
<p>At first glance, Destino looks like a Doom stunt. And honestly, it is.</p>
<p>But there’s more to it: Destino changes the conversation for teams with native code they can’t easily replace.</p>
<p>Many companies have C libraries, shared objects, or DLLs that still do important work. They might calculate pricing, parse old formats, talk to hardware, run simulations, or hold domain knowledge no one wants to rewrite. Modernizing is usually tough: you either wrap it in a service, rewrite it over years, or freeze the whole system because one native part is too risky to change.</p>
<p>FFI gives those teams another option: keep the native library that works, wrap it with a Node.js app, and improve the runtime, deployment, observability, and integration—without pretending the old code has to vanish right away.</p>
<p>That doesn’t make the hard parts disappear. You still need to be careful with ABI, memory ownership, concurrency, failure modes, and versioning. FFI makes the boundary easier to set up, but it’s not something you can ignore.</p>
<p>Still, it’s hard to ignore: if a JavaScript loop can run a native Doom engine at 35 fps in a terminal, it can probably call the legacy C library your business relies on.</p>
<p><em>Want to know more about FFI and our Project Destino?</em><br /><em>We dedicated a full episode of our podcast "</em><a href="https://open.spotify.com/show/0cjrbI217FlGr0oopolcON?si=HUPPosbyRMun_Mw67WcFjQ"><em>The Node (and More) Banter</em></a><em>".</em></p>
<hr />
<h2><strong>What comes next</strong></h2>
<p>Destino opens the door to more experiments. The same approach could work for <code>llama.cpp</code>, GPU libraries, local AI inference, native graphics, or any old code that’s useful but hard to reach from JavaScript. Maybe the next demo will use NVIDIA GPUs. Maybe it’ll be <a href="https://github.com/DarthJDG/OpenPrince">Prince of Persia</a>.</p>
<p>The specific demo matters less than how the integration works: JavaScript runs the app, native code does the specialized work, and FFI keeps the boundary small.</p>
<p>Platformatic didn’t port Doom because it was practical. We did it because the technology made it possible. Sometimes, that’s all you need to show where the real work begins.</p>
]]></content:encoded></item><item><title><![CDATA[Ahead of Time Scaling: How Platformatic ICC Predicts and Provisions]]></title><description><![CDATA[How Platformatic ICC uses predict autoscaling to provision K8S pods ahead of demand, reduce latency, & outperforming HPA & KEDA for Node.js workloads.]]></description><link>https://blog.platformatic.dev/ahead-of-time-scaling-platformatic-icc-predictive-autoscaling</link><guid isPermaLink="true">https://blog.platformatic.dev/ahead-of-time-scaling-platformatic-icc-predictive-autoscaling</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[autoscaling]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[performance]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[watt]]></category><category><![CDATA[#ICC]]></category><category><![CDATA[scalability]]></category><dc:creator><![CDATA[Ivan Tymoshenko]]></dc:creator><pubDate>Thu, 30 Apr 2026 14:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/8b04850c-b3e7-43ea-b9e8-39e86e7bf57b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most Kubernetes autoscalers work the same way: they check a metric, compare it to a threshold, and then add pods. The issue is that by the time the metric crosses the threshold, the application is already overloaded. New pods take time to start (we’re talking in the realm of  1-4 minutes here, and that’s <em>if</em> you have the compute resources readily available) and begin handling traffic, so during that period, the existing pods handle all the load. This means for 2-4 minutes <em>(or upwards of 10 if your cluster is out of available compute)</em>, users end up seeing slow responses or errors, not because scaling failed, but because it happened too late. That’s more than enough time to make a negative impact on your business <em>(abandoned carts, logged-off streamers, the works)</em>.</p>
<p>The <a href="https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/">Horizontal Pod Autoscaler (HPA)</a> is the most common scaler in Kubernetes. It runs a control loop that checks the current metric value, usually CPU usage, and calculates how many pods are needed based on the ratio of the current value to the target. For Node.js apps, CPU isn't a great metric: the event loop can be overloaded and queuing requests even when CPU usage looks normal. HPA doesn't support metrics like Event Loop Utilization (<em>ELU</em>) by default; you need a custom metrics setup with Prometheus and an adapter to use those.</p>
<p><a href="https://keda.sh/">KEDA</a> addresses the metric issue by extending HPA with many event-driven triggers, like Prometheus queries, message queues, and HTTP request rates. This makes it easy to scale on ELU or other custom metrics. However, the underlying scaling logic is unchanged: each check is just a snapshot of the current value, with no sense of past trends or whether the metric is going up or down. KEDA gives you better metrics, but still uses the same reactive approach.</p>
<p>Reactive scaling is especially tough on Node.js apps for some of the reasons we’ve already mentioned. Namely, CPU utilization is not just a lagging metric on ELU performance <em>(what really matters for Node.js)</em>, but one that sometimes doesn’t even correlate to ELU as you might expect. The event loop runs JavaScript one callback at a time, and when it gets overloaded, performance doesn't just slow down gradually; it drops off sharply. Latency increases quickly until the app can barely make progress. The kicker is that all this happens before the HPA even knows it needs to scale more pods.</p>
<p>Unfortunately, this is much more than a simple configuration issue. Lowering the threshold doesn't make the scaler react any faster; it just makes it respond to a lower value <em>(saw, lower CPU utilization)</em>. In practice, particularly when taking this approach for running high-traffic Node.js apps, this  means you'll always have more pods running than you need. <em>(This can really add up more than you might realize. We’ve seen some pretty drastically over-provisioned clusters and scaling policies - we are talking up to 7-figures in excess cloud spend per major scaling event.)</em></p>
<p>So - what if instead of scaling <strong>reactively,</strong> you could scale… <strong>proactively?</strong> What might such a system look like?</p>
<p>Well, you probably guess where we’re going.</p>
<p>Platformatic ICC (<em>“Intelligent Command Center”</em>) takes a different approach. Rather than waiting for a metric to hit a threshold, ICC watches the load trend over time and predicts where it will be when a new pod is ready. If it looks like more capacity will be needed, ICC adds pods right away, so they're ready when the extra load arrives.</p>
<p>Benchmarks show a clear difference: with steady traffic increases, ICC kept median response latency at 26 ms, while KEDA reached 154 ms and HPA hit 522 ms:</p>
<table style="min-width:100px"><colgroup><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col></colgroup><tbody><tr><td><p></p></td><td><p><strong>ICC</strong></p></td><td><p><strong>KEDA</strong></p></td><td><p><strong>HPA</strong></p></td></tr><tr><td><p>Success Rate</p></td><td><p>99.47 %</p></td><td><p>95.11 %</p></td><td><p>90.97 %</p></td></tr><tr><td><p>Avg. Latency</p></td><td><p>167 ms</p></td><td><p>1,174 ms</p></td><td><p>1,499 ms</p></td></tr><tr><td><p>Median Latency</p></td><td><p>26 ms</p></td><td><p>154 ms</p></td><td><p>522 ms</p></td></tr><tr><td><p>p(90) latency</p></td><td><p>317 ms</p></td><td><p>3,530 ms</p></td><td><p>4,168 ms</p></td></tr><tr><td><p>p(99) latency</p></td><td><p>1,970 ms</p></td><td><p>10,001 ms</p></td><td><p>10,001 ms</p></td></tr><tr><td><p>Errors</p></td><td><p>718</p></td><td><p>6,591</p></td><td><p>12,039</p></td></tr></tbody></table>

<p>Below we will cover:</p>
<ol>
<li><p>Some basics on the event loop, latency, and the structural incompatibilities Node.js has with traditional scaling methods.</p>
</li>
<li><p>How reactive scalers like the HPA and KEDA work</p>
</li>
<li><p>Overview the ICC and its predictive scaling algorithm</p>
</li>
<li><p>Do some load testing and compare benchmarks.</p>
</li>
</ol>
<p>Let’s dig in.</p>
<hr />
<h2><strong>The Node.js event loop and the latency cliff</strong></h2>
<p>We’ll start with a quick review of some Node.js and JavaScript basics. The heart of Node.js is the <strong>event loop</strong>, which runs JavaScript callbacks one at a time on a single thread. It cycles through different phases, picking up ready callbacks and running them in order.</p>
<p>A typical HTTP request shows how this works. When a request comes in, the event loop runs the handler callback, which parses data, checks the input, and runs business logic. This part is synchronous, so nothing else can happen in the loop at the same time. If the handler needs to access a database or call an external API, Node.js hands off that work to the operating system or a background thread pool, and the event loop moves on to other callbacks. When the I/O finishes, a new callback is added to the queue, and the event loop picks it up later to finish processing, like reading the database result and sending the response.</p>
<p>This design is what makes Node.js efficient. At any time, an app might have hundreds of requests in progress, but most are just waiting for I/O and not using the event loop. One thread can handle thousands of connections with little overhead, since there's no context switching or lock contention. This efficiency relies on the event loop having some idle time between callbacks.</p>
<p>As traffic grows, the synchronous parts of handling requests—like parsing bodies, serializing JSON, running business logic, or rendering server-side React—start to use up more of the idle time. While this code runs, nothing else can happen. Eventually, those idle gaps disappear.</p>
<p><a href="https://nodesource.com/blog/event-loop-utilization-nodejs">Event Loop Utilization</a> (<em>ELU</em>) measures this effect. It's a value from 0 to 1 that shows how much time the event loop spends running code versus being idle. An ELU of 0.5 means the loop is active half the time, while 0.9 means there's almost no idle time left.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/41937785-6d10-41e7-9207-6f0eb7e31a72.png" alt="Latency-Cliff" style="display:block;margin:0 auto" />

<p>Trouble begins when ELU gets close to 1.0. Now, the loop has no idle time left, so every new request arrives while the previous one is still being processed. Callbacks start to pile up. With almost no idle gaps, even a small traffic increase can make wait times jump from milliseconds to seconds.</p>
<p>This is what we call the cliff. When ELU reaches 1.0, the app enters a feedback loop: the queue grows, each request takes longer because it waits behind more requests, and the loop stays saturated, making the queue grow even more. Response times don’t just increase linearly now, but hyperbolically. The app hasn't crashed, but it's no longer making real progress. Responses that used to take 30 ms now take 5 seconds or even hit the client timeout. You can see this in our <a href="https://platformatic.github.io/node-server-capacity-model/index.html">interactive capacity model</a>: adjust the processing time and traffic rate, and you'll notice response times stay low until about 70–80% utilization, then suddenly spike as the event loop gets saturated.</p>
<p>That's why waiting to scale up a Node.js app until after ELU crosses the threshold is so harmful. By the time HPA or KEDA notices and adds pods, the event loop has already gone over the cliff. The queue grows faster than the loop can handle, and every new request just adds to the problem. The pod can't recover on its own while traffic stays high, and it will stay stuck in this feedback loop for the 1 to 4minutes it takes new pods to start and take on traffic.</p>
<p>To put it another way, the HPA can get away with using pod CPU utilization for most runtimes (Java, .NET, etc.) because CPU utilization is actually a fairly accurate representation of how loaded that app is. Therefore, using that metric makes sense to determine when to scale new pods. <em>(Again, this still will be</em> <em><strong>reactive</strong></em>*, but at least it’s reacting to a reasonable metric.)*</p>
<p>That correlation between CPU and application load doesn’t exist with Node.js. This compounds the problem with reactive scaling for Node.js apps in particular because you are scaling on a metric that doesn’t strongly correlate to your application's actual load.</p>
<hr />
<h2>How reactive scalers work <em>(and why they're always late)</em></h2>
<p>To see why predictive scaling is important, let's look at how the most popular Kubernetes scalers actually make scaling decisions.</p>
<h3><strong>HPA: one number, one formula</strong></h3>
<p>The Kubernetes <a href="https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/">Horizontal Pod Autoscaler (HPA)</a> runs a control loop every 15 seconds. On each cycle, it fetches the current metric value from the Metrics Server (typically CPU utilization) and computes the desired replica count with a single formula:</p>
<pre><code class="language-plaintext">desiredReplicas = ceil(currentReplicas × (currentValue / targetValue))
</code></pre>
<p>For example, if 4 pods are running at 90% CPU with a 70% target:</p>
<pre><code class="language-plaintext">desiredReplicas = ceil(4 × (90 / 70)) = ceil(5.14) = 6
</code></pre>
<h3><strong>Why HPA is the wrong choice for Node.js</strong></h3>
<p>HPA uses CPU utilization by default, and most teams stick with that. But for Node.js apps, this isn't a good match. As mentioned earlier, Event Loop Utilization (<em>ELU</em>) is the metric that really shows if a Node.js app is overloaded, and CPU doesn't reflect that. The event loop can be maxed out while CPU usage looks normal, or the other way around.</p>
<p>HPA doesn't support ELU by default. It works with the Metrics Server, which only provides CPU and memory. To scale on ELU, you need to set up a custom metrics pipeline using Prometheus, a Prometheus adapter, and a custom metric query. <em>(Yes -</em> <a href="https://github.com/platformatic/platformatic"><em>we can help with that!</em></a><em>)</em></p>
<h3><strong>KEDA: right metric, same logic</strong></h3>
<p><a href="https://keda.sh/">KEDA</a> builds on HPA by adding many event-driven triggers, like message queues, HTTP request rates, Prometheus queries, and more. This makes it easy to scale on custom metrics like ELU without having to build a full custom metrics pipeline.</p>
<p>But the scaling logic doesn't change. When scaling from 1 to N replicas, KEDA creates an HPA object behind the scenes and gives it the external metric value. It uses the same formula and snapshot-based checks. KEDA gives you better metrics, but the way it decides when to scale is still the same. <em>(Different data, same algorithm.)</em></p>
<p>By default, KEDA checks metrics every 30 seconds, which is twice as slow as HPA. In our benchmarks, we set it to 15 seconds to match HPA and make the comparison fair.</p>
<h3><strong>The core limitations</strong></h3>
<p>Even if you use the right metric, the reactive approach has basic limitations that can't be fixed by changing settings.</p>
<p><strong>The startup gap</strong>. After a reactive scaler decides to add pods, there is a delay before those pods are useful:</p>
<ol>
<li><p>The scaler detects the threshold has been crossed <em>(up to 15–30s depending on polling interval)</em></p>
</li>
<li><p>Kubernetes schedules the new pod and pulls the container image</p>
</li>
<li><p>The application starts and initializes</p>
</li>
<li><p>The readiness probe passes</p>
</li>
<li><p>The load balancer begins routing traffic to the new pod</p>
</li>
</ol>
<p>In real enterprise settings, this can take anywhere from 1 minute to upwards of 4 minutes. During that time, the existing pods handle all the traffic. By the time new pods are ready, the app might have already spent over 2 minutes overloaded. For Node.js apps, this is when performance drops off sharply.</p>
<p><strong>The saturation cap</strong>. When the metric has a natural cap (<em>like ELU, which maxes out at 1.0)</em>, the scaler loses visibility into the actual load. A pod at ELU 1.0 could need one more pod or ten more, but the formula sees the same number either way. The true load is hidden behind the cap. This forces the scaler into a staircase pattern: it adds pods based on what it can see, waits for the new pods to also become saturated, and only then realizes more are needed, which compounds the problem. Each step requires a full cycle of pod startup and saturation before the next decision can be made. The scaler cannot reach the right pod count in one step because it never sees the right number, leading to spiraling performance problems.</p>
<p><strong>Redistribution problem.</strong> Every time HPA or KEDA adds a pod, it creates a temporary distortion in the metrics. The new pod starts receiving traffic immediately, but the existing pods don't shed their load at the same pace: queues take time to drain, in-flight requests must complete, and garbage collection needs to settle. During this transition, the new pod's metric is rising while the old pods' metrics haven't dropped yet. The scaler sees the sum go up and interprets it as growing demand, when it's actually just the overlap of old and new pods, both holding load at the same time. This can lead the scaler to add pods that aren't needed. ICC handles this with a dedicated redistribution stage that gradually includes new pods' metrics over time, filters out the artificial drop from load shedding, and still lets real load increases pass through immediately, no cooldown required <em>(</em><a href="https://arxiv.org/abs/2604.19705"><em>see the algorithm whitepaper</em></a> <em>for details)</em>.</p>
<p>All these issues come from the same cause: traditional scalers like the HPA or KEDA look at scaling metrics in isolation; as in, without the contextual data of whether that metric has been trending up or down over a given time period. Instead, the scaler treats each check as separate. It looks at one value, compares it to a target, and acts, without knowing if the metric is going up, down, or staying the same. It also can't account for the delay between making a decision and when new capacity is actually available, and how that extra capacity might impact the metric it’s measuring to make its scaling decisions.</p>
<hr />
<h2><strong>Intelligent Command Center</strong></h2>
<p>Platformatic <a href="https://github.com/platformatic/blog-posts/blob/main/icc-predictive-scaling/blog.md#the-nodejs-event-loop-and-the-latency-cliff">Intelligent Command Center (ICC)</a> is a cloud control plane that provides intelligent management, monitoring, and optimization of Node.js applications deployed in Kubernetes. Applications run on <a href="https://docs.platformatic.dev/">Platformatic Watt</a>, the Platformatic runtime for running high-performance Node.js apps. A single Watt instance can host multiple Node.js applications, each in its own worker thread within the same process. In a Kubernetes deployment, each pod runs one Watt instance (<em>and each Watt instance could run multiple Node.js apps as worker threads</em>).</p>
<p>A companion module, <a href="https://github.com/platformatic/watt-extra">@platformatic/watt-extra</a>, runs alongside Watt in each pod. It collects runtime metrics (<em>including ELU and heap usage</em>) and sends them to ICC, which uses them to make scaling decisions.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/bf5228be-bd00-41c2-8838-0cf6433882e2.png" alt="Data Flow In Platformatic ICC" style="display:block;margin:0 auto" />

<p><strong>Data flow in ICC.</strong> Each pod runs a Watt instance hosting one or more applications. Watt measures per-application metrics (<em>like ELU</em>); Watt-Extra collects them into batches and sends them to ICC. ICC runs the algorithm pipeline and updates the Kubernetes Deployment replica count.</p>
<hr />
<h2><strong>How ICC's predictive scaling works</strong></h2>
<h3><strong>The idea</strong></h3>
<p>A reactive scaler asks: "Is the application overloaded right now?" and acts on the answer. By the time new pods are ready, the answer has changed, usually for the worse.</p>
<p>ICC takes a different approach and asks, "Will the app be overloaded by the time a new pod is ready?" If so, it scales up right away, so the extra capacity is available when needed. This shifts scaling from reacting to what's happening now to acting based on a forecast.</p>
<p>To build that forecast, ICC tracks the load trend over time: not just the current value, but whether it is rising, falling, or stable, and how fast. It extrapolates the trend forward by the time it takes a new pod to start and begin serving traffic. If the projected load exceeds the capacity of the current pod count, ICC adds pods immediately. The full details of the algorithm are described in the <a href="https://arxiv.org/abs/2604.19705">algorithm whitepaper</a>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/6114fe78-940c-4e81-a2fb-c5cc39f805a7.png" alt="Prediction" style="display:block;margin:0 auto" />

<p>The chart shows ELU per pod over the last 20 seconds. The solid line (M<em>t</em>) has been rising steadily. Right now it's at 0.73 (M<em>now</em>), just below the 0.75 threshold (<em>dashed red line</em>). HPA or KEDA would look at this value, see that it hasn't crossed the threshold, and do nothing. ICC sees the trend and projects that by the time a new pod would be ready (the prediction horizon <em>H</em>), the metric will reach 0.78 (M<em>h</em>), above the threshold. So it scales up now, before the overload begins.</p>
<p>The rest of this section explains how the algorithm builds this prediction.</p>
<p><strong>The core idea.</strong> The algorithm takes per-pod metric values (<em>like ELU on each pod</em>), combines them into a single cluster-wide number, predicts where that number is heading, and converts the prediction back into a per-pod value to compare against the threshold. This aggregate-predict-project flow is the backbone of the algorithm.</p>
<p><strong>Why predict on an aggregate?</strong> Per-pod metrics change for two reasons: external traffic changes and the scaler's own actions. When the scaler adds a pod, the load balancer starts routing traffic to it, and ELU on the existing pods drops, even though external traffic hasn't changed at all. If the algorithm predicted the trend from per-pod ELU, it would see this drop as "load is decreasing" and might delay further scaling when it's actually needed. The algorithm avoids this by summing ELU across all pods into a cluster-wide aggregate. When a pod is added, and load redistributes, individual ELU values shift, but the total stays approximately the same (<em>the same total work is spread across more pods</em>). The aggregate reflects external traffic changes without being distorted by scaling actions, giving the algorithm a stable signal to predict from.</p>
<p><strong>Cleaning the data.</strong> Raw metric data is not ready for prediction. Pods send measurements in batches at different times, so at any given moment, some pods have reported recent data and others haven't. After a scale-up, new pods create temporary distortions in the metrics. Three preprocessing stages handle this before the aggregate reaches the prediction stage.</p>
<p><em>Alignment</em> places irregularly-timed samples onto a uniform time grid (<em>e.g., one tick per second</em>) by interpolation, so values from different pods can be compared at the same points in time.</p>
<p><em>Imputation</em> estimates values for pods that haven't been reported yet. At each tick, the algorithm takes the previous total, subtracts the previous values of pods that have now reported new data, and uses the remainder as the estimated contribution of the pods still missing. When a late batch arrives, the estimates are replaced by real data and the totals are recomputed.</p>
<p><em>Redistribution</em> smooths out the metric distortion after a scale-up. New pods' values are included gradually (their contribution ramps from zero to full over a stabilization period) rather than appearing all at once. At the same time, the artificial drop on existing pods as they shed load is absorbed: the algorithm allows the aggregate to rise (to catch real traffic increases) but prevents it from dropping while new pods are still stabilizing. This way, redistribution artifacts are filtered out, but real load changes pass through immediately.</p>
<p><strong>Predicting the trend.</strong> The cleaned aggregate enters the prediction stage, which uses <a href="https://doi.org/10.1016/j.ijforecast.2003.09.015">Holt's double exponential smoothing</a>. This method maintains two values at each tick: the <em>level</em> (a smoothed estimate of where the aggregate is now) and the <em>trend</em> (<em>how fast the aggregate is changing</em>). Each new data point updates both. The level tracks the signal while filtering single-tick noise. The trend builds gradually over multiple ticks, converging to the actual rate of change. A single noisy tick pushes the level only slightly while the trend absorbs the rest. This lets the smoothing be aggressive enough to filter noise while still reacting quickly to sustained changes.</p>
<p><strong>Asymmetric reaction.</strong> The algorithm uses different smoothing parameters for upward and downward movements. When the metric rises faster than the forecast, the algorithm picks it up quickly (<em>both the level and the trend react aggressively</em>) because missing a spike means the application enters the latency cliff before the scaler can respond. When the metric drops, the algorithm follows slowly, letting the downward trend build over many ticks before acting on it. A brief dip might be noise, and scaling down too eagerly risks having to scale right back up. This reflects the reality that under-provisioning is immediately damaging, while brief over-provisioning only costs resources.</p>
<p><strong>The prediction horizon.</strong> The horizon <em>H</em> determines how far into the future the algorithm looks when extrapolating the trend. It is derived from observed pod startup times: how long it actually takes a new pod to be scheduled, initialized, and ready to serve traffic. ICC measures this from real-scale-up events in the cluster and adapts over time, so the horizon tracks actual infrastructure conditions rather than relying on a hardcoded constant. A multiplier extends the horizon slightly beyond the measured startup time to provide a safety buffer, and configurable floor and ceiling bounds prevent the horizon from becoming too short (<em>which would reduce the algorithm's effectiveness</em>) or too long (which would make the extrapolation unreliable).</p>
<p><strong>Handling metric saturation.</strong> Some metrics have a natural cap. ELU maxes out at 1.0: once the event loop is fully saturated, ELU cannot rise further, no matter how much more traffic arrives. Without special handling, the trend would decay to zero during saturation (<em>the level stops rising because the input is clipped</em>), and the algorithm would stop scaling even though the load is still growing behind the cap. ICC handles this by preserving the trend during saturation: the trend is allowed to increase but never decrease while the metric is clipped, so the algorithm continues to scale up even when the signal is flat at its maximum.</p>
<p><strong>The scaling decision.</strong> The prediction stage produces a predicted aggregate (A<em>H</em>): the forecasted total load at the horizon. The decision stage converts this back into a per-instance value by dividing by the current pod count, producing the projected per-pod metric at the horizon (M<em>H</em>). This is what the chart shows. If M<em>H</em> exceeds the threshold <em>τ</em>, the algorithm computes how many pods are needed to keep the per-instance metric below the threshold and scales up immediately. If the trend is flat or falling and the metric is within the threshold, it considers scaling down, with a safety margin to avoid immediately scaling right back up.</p>
<p>The full algorithm, including the mathematical formulation and worked examples, is described in the <a href="https://arxiv.org/abs/2604.19705">algorithm whitepaper</a>.</p>
<h3><strong>Signals</strong></h3>
<p>Accurate forecasting depends on good data. If you average metrics over 15 seconds, you lose the details that matter for short-term prediction—a sharp spike in the last 5 seconds looks the same as a slow rise over 15. This makes trend estimates and forecasts less precise. ICC uses raw metric samples instead. Each pod sends every measurement to ICC in batches, with no averaging or data loss. The batch timing adjusts based on load: under heavy traffic, batches go out every 5 seconds for fresh data; when idle, they go out every 40 seconds to save resources. This way, a spike that started 5 seconds ago is seen right away, not hidden in a delayed average.</p>
<hr />
<h2><strong>Benchmarks</strong></h2>
<p>To measure the difference predictive scaling makes in practice, we tested ICC against HPA and KEDA under identical conditions on the same cluster with the same application.</p>
<h3><strong>Test setup</strong></h3>
<p>A Next.js 16 e-commerce application (App Router, Server Components, SSR) runs on Platformatic Watt with one worker per pod (<em>1 CPU / 2 GB RAM</em>). An Envoy proxy with 30-second linear slow start sits between the load balancer and the pods, ramping traffic to new pods gradually so that V8 JIT compilation on cold code paths does not distort the comparison.</p>
<p>All three scalers operate on the same deployment (<em>min 4, max 20 pods</em>):</p>
<ul>
<li><p><strong>ICC</strong>, predictive scaling on ELU with a 0.7 threshold</p>
</li>
<li><p><strong>KEDA</strong>, scaling on ELU (<em>via Prometheus query</em>) with a 0.7 threshold</p>
</li>
<li><p><strong>HPA</strong>, scaling on CPU utilization with a 70% target</p>
</li>
</ul>
<p>KEDA uses the same metric and threshold as ICC, so the comparison isolates the scaling algorithm. HPA is included because it is the most widely deployed Kubernetes scaler; its results reflect the choice of metric (<em>CPU instead of ELU</em>) in addition to the reactive algorithm.</p>
<p>The benchmark ran on AWS EKS (<em>us-east-1</em>), Kubernetes v1.35, with 4 worker nodes (<em>m5.2xlarge: 8 vCPU, 32 GB RAM each</em>). Load was generated from a dedicated EC2 instance (<em>c7gn.2xlarge, ARM64</em>) in the same VPC using <a href="https://k6.io/">Grafana k6</a>. The full benchmark automation, scaler configurations, and raw data are available in the <a href="https://github.com/platformatic/k8s-watt-performance-demo/tree/scaler">benchmark repository</a>.</p>
<p>Each chart below shows three traces: the average ELU across all pods (<em>purple, left axis</em>), the pod count (<em>green, right axis</em>), and the target request rate (<em>grey shaded area</em>). The dashed red line marks the ELU threshold of 0.7.</p>
<h2><strong>Steady ramp</strong></h2>
<p>Traffic grows from 10 to 800 req/s over ~2.5 minutes, then holds at 800 req/s for 90 seconds. This is the most common real-world pattern: traffic grows gradually as users arrive over the course of minutes.</p>
<h3><strong>ICC</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/1ad4cb15-c940-4b9a-afca-0e424ad31066.png" alt="ICC Ramp" style="display:block;margin:0 auto" />

<p>The predictive algorithm keeps ELU below the 0.7 threshold. It watches the trend, predicts where ELU is heading, and scales up ahead of time to match capacity. It also avoids over-provisioning by using only as many pods as needed to keep ELU near the threshold.</p>
<h3><strong>KEDA</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/fea70555-8bc6-424f-8819-a82dc36d4df2.png" alt="KEDA Ramp" style="display:block;margin:0 auto" />

<p>KEDA uses the same metric and threshold, but since it's reactive, it waits for ELU to cross the threshold before scaling. This means it can't keep ELU below the threshold during traffic increases, and average ELU hits 0.92 at the peak. The problem gets worse as overloaded pods slow down non-linearly due to queuing, eventually forcing the scaler to add even more pods.</p>
<p>Lowering the threshold doesn't fix the problem. It doesn't make the scaler react <em>faster;</em> it just makes it respond to a <em>lower value</em>. The app then runs at a lower utilization all the time, using more pods for the same load. This means you always pay for extra capacity, not just during spikes.</p>
<h3><strong>HPA</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/24e07068-91fa-4bf2-b492-8669be631344.png" alt="HPA Ramp" style="display:block;margin:0 auto" />

<p>HPA behaves like KEDA, but it scales based on CPU usage instead of ELU. Since CPU isn't a measure of a Node.js application's health, we see that ELU stays elevated for the majority of our load test.</p>
<h3><strong>Comparing the results</strong></h3>
<p>How the scaler works directly affects what users experience. When ELU stays below the threshold, the event loop handles requests quickly. But if ELU goes over the threshold, queues and delays grow, and response times can reach the client timeout.</p>
<table style="min-width:100px"><colgroup><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col></colgroup><tbody><tr><td><p></p></td><td><p><strong>ICC</strong></p></td><td><p><strong>KEDA</strong></p></td><td><p><strong>HPA</strong></p></td></tr><tr><td><p>Success Rate</p></td><td><p>99.47 %</p></td><td><p>95.11 %</p></td><td><p>90.97%</p></td></tr><tr><td><p>Avg. latancy</p></td><td><p>167 ms</p></td><td><p>1,174 ms</p></td><td><p>1,499 ms</p></td></tr><tr><td><p>Median latency</p></td><td><p>26 ms</p></td><td><p>154 ms</p></td><td><p>522 ms</p></td></tr><tr><td><p>p(90) latency</p></td><td><p>317 ms</p></td><td><p>3,530 ms</p></td><td><p>4,168 ms</p></td></tr><tr><td><p>p(99) latency</p></td><td><p>1,970 ms</p></td><td><p>10,001 ms</p></td><td><p>10,001 ms</p></td></tr><tr><td><p>Errors</p></td><td><p>718</p></td><td><p>6,591</p></td><td><p>12,039</p></td></tr></tbody></table>

<p>ICC kept ELU close to the threshold, with a 99.47% success rate and 317 ms at the 90th percentile. KEDA and HPA spent a lot of time above the threshold: KEDA lost 5% of requests, and HPA lost 9%. Their 99th percentile latencies hit the 10-second client timeout because queues grew faster than the event loop could handle.</p>
<h2><strong>Sudden spike</strong></h2>
<p>In this test, traffic jumps from 0 to 800 requests per second in 10 seconds, then stays at 800 for 2 minutes. No scaler can stop the initial overload—there's no trend history to predict from and no time to start new pods. The real question is how fast each scaler recovers.</p>
<h3><strong>ICC</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/8cafdb83-5866-4bc4-a526-f664bc92dd70.png" alt="ICC Spike" style="display:block;margin:0 auto" />

<p>Without any trend history, ICC can't predict the spike. But as soon as the first data comes in, it quickly builds a trend estimate and starts scaling aggressively. The algorithm keeps scaling even when ELU is maxed out at 1.0, maintaining the trend through saturation instead of being fooled by the cap.</p>
<h3><strong>KEDA</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/d16648ac-fe70-4516-8c9d-ab953b2969d3.png" alt="KEDA Spike" style="display:block;margin:0 auto" />

<p>The reactive formula scales in proportion to the current overload ratio, but each decision is based on a single snapshot. It cannot account for the fact that the load arrived all at once, and more capacity is needed than the current ratio suggests. The result is a staircase of incremental scale-ups, each insufficient, while ELU remains elevated.</p>
<h3><strong>HPA</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/aba2f302-ebda-48d6-8f0e-7e2d88a0be55.png" alt="HPA Spike" style="display:block;margin:0 auto" />

<p>HPA has the same reactive limitation as KEDA, but it's even worse because it uses CPU utilization, which lags behind event loop saturation in Node.js apps. The scaler doesn't see the real urgency, so it scales up even more slowly.</p>
<table style="min-width:100px"><colgroup><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col></colgroup><tbody><tr><td><p></p></td><td><p><strong>ICC</strong></p></td><td><p><strong>KEDA</strong></p></td><td><p><strong>HPA</strong></p></td></tr><tr><td><p>Success Rate</p></td><td><p>91.51 %</p></td><td><p>87.47 %</p></td><td><p>77.31 %</p></td></tr><tr><td><p>Avg latency</p></td><td><p>1,126 ms</p></td><td><p>1,989 ms</p></td><td><p>2,205 ms</p></td></tr><tr><td><p>Median latency</p></td><td><p>55 ms</p></td><td><p>855 ms</p></td><td><p>1,102 ms</p></td></tr><tr><td><p>p(90) latency</p></td><td><p>3,385 ms</p></td><td><p>6,108 ms</p></td><td><p>7,338 ms</p></td></tr><tr><td><p>p(99) latency</p></td><td><p>10,001 ms</p></td><td><p>10,001 ms</p></td><td><p>10,001 ms</p></td></tr><tr><td><p>Errors</p></td><td><p>8,028 </p></td><td><p>11,212</p></td><td><p>21,067</p></td></tr></tbody></table>

<p>All three scalers struggle during the initial burst—the 99th percentile latency hits the 10-second client timeout for all of them. The difference is in how they recover. ICC's median latency drops to 55 ms after the burst, so most requests are served normally. KEDA (855 ms) and HPA (1,102 ms) stay slow throughout the test, and HPA loses almost a quarter of all requests.</p>
<hr />
<h2><strong>Conclusion</strong></h2>
<p>Reactive scaling has a built-in limit. No matter how you adjust HPA or KEDA, they'll always spot overload after it starts, scale up after the damage is done, and have trouble handling the effects of their own actions.</p>
<p>Predictive scaling with ICC gets rid of this problem. By watching the load trend and forecasting where it will be when new pods are ready, ICC scales up before demand hits. The benchmarks show the impact: median latency is six times lower than KEDA, twenty times lower than HPA, and ICC achieves a 99.47% success rate during heavy traffic.</p>
<p>This also changes how you manage your baseline. If you can't trust your scaler to handle spikes smoothly, you keep extra pods running as a safety net, which means paying for idle capacity all the time. But if your scaler can add pods ahead of time without hurting performance, you can run closer to real demand. Predictive scaling not only boosts performance under load—it also cuts costs when traffic is low.</p>
<p>ICC is available now. To get started:</p>
<ul>
<li><p><a href="https://icc.platformatic.dev/">Platformatic ICC</a></p>
</li>
<li><p><a href="https://arxiv.org/abs/2604.19705">Algorithm whitepaper</a></p>
</li>
<li><p><a href="https://github.com/platformatic/k8s-watt-performance-demo/tree/scaler">Benchmark repository</a></p>
</li>
</ul>
<p>If you’re running high-traffic systems, we’d love to chat! Drop us a note at hello@platformatic or reach out to us on LinkedIn.</p>
<p>Thanks and happy building!</p>
]]></content:encoded></item><item><title><![CDATA[Run Medusa on Kubernetes with Watt
as a Monorepo]]></title><description><![CDATA[How to run Medusa on K8s using a Watt monorepo. Simplify your e-commerce stack with single deployment, shared dependencies, and improved performance.]]></description><link>https://blog.platformatic.dev/run-medusa-kubernetes-watt-monorepo</link><guid isPermaLink="true">https://blog.platformatic.dev/run-medusa-kubernetes-watt-monorepo</guid><category><![CDATA[medusa]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[platformatic]]></category><category><![CDATA[monorepo]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[watt]]></category><dc:creator><![CDATA[Paolo Insogna]]></dc:creator><pubDate>Tue, 28 Apr 2026 14:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/03fd7b26-e637-4b53-bf00-378d94dbf22d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://medusajs.com">Medusa</a> stands out as a flexible open source commerce platform for Node.js. It offers teams a customizable backend, admin tools, and a modern storefront, all without locking you into a strict SaaS model. This makes it ideal for teams who want to move quickly and keep control over their architecture.</p>
<p>Running Medusa in production is more than just starting a single process. The real challenge is keeping the entire commerce stack fast, organized, and easy to update, especially when you have a backend, storefront, admin UI, image optimization, internal networking, and Kubernetes involved.</p>
<p>This is where using a Watt monorepo really helps.</p>
<p><a href="https://www.platformatichq.com/watt">Watt</a> is Platformatic’s tool for combining multiple Node.js apps into one deployable unit by running them as worker threads under a single process.</p>
<p>Medusa can be deployed in a Kubernetes environment. To manage, monitor, and optimize your application in this setting, you can use the <a href="https://icc.platformatic.dev">Intelligent Command Center (ICC)</a>. ICC is a sophisticated cloud control plane that provides intelligent management, monitoring, and optimization of cloud-native applications deployed in Kubernetes environments. ICC offers enterprise-grade features for application lifecycle management, intelligent autoscaling, compliance monitoring, and comprehensive observability.</p>
<p>For basic deployment, simply running Watt on Kubernetes is sufficient.</p>
<p>Rather than spreading complexity across multiple repos, custom Dockerfiles, and manual service connections, you can keep everything in one workspace and let Watt manage it as a single platform. This gives you one dependency graph, one build process, one deployment artifact, and a single place to manage the rules that keep your system running smoothly.</p>
<p>In this post, we will look at a working <a href="https://medusajs.com">Medusa</a> setup deployed on <a href="https://icc.platformatic.dev">ICC</a> with:</p>
<ul>
<li><p><code>web/backend</code>: Medusa backend via <code>@platformatic/node</code></p>
</li>
<li><p><code>web/frontend</code>: Medusa Next.js starter via <code>@platformatic/next</code></p>
</li>
<li><p><code>web/gateway</code>: public routing via <code>@platformatic/gateway</code></p>
</li>
<li><p><code>image-server</code>: a dedicated <code>@platformatic/next</code> image optimizer application that reuses the same codebase as <code>web/frontend</code></p>
</li>
</ul>
<p>This set-up can be both far easier to manage <em>and</em> more performant. Let’s explore.</p>
<h2><strong>Why a monorepo is a good fit for Medusa</strong></h2>
<p>Medusa already pushes you toward a multi-application architecture. Even in a relatively standard deployment, you are dealing with:</p>
<ul>
<li><p>a backend API</p>
</li>
<li><p>an admin UI</p>
</li>
<li><p>a storefront</p>
</li>
<li><p>image optimization</p>
</li>
<li><p>environment variables shared across services</p>
</li>
<li><p>public and internal URLs that must stay aligned</p>
</li>
</ul>
<p>You can spread these parts across different repositories and deployment pipelines, but as soon as you do, even simple changes become complicated.</p>
<p>For example, changing a base path means updating several repos. Keeping React versions consistent gets harder. Coordinating Docker changes turns into a big release task. Even figuring out if the storefront is calling the right backend can take more effort than it should.</p>
<p>With Watt, the monorepo becomes the control plane for the whole stack.</p>
<ul>
<li><p>Each application stays isolated as a worker thread with Watt.</p>
</li>
<li><p>The whole platform is configured in one place.</p>
</li>
<li><p>Internal service discovery comes for free.</p>
</li>
<li><p>Deployment stays a single build and a single runtime entry point.</p>
</li>
</ul>
<p>This approach gives you the best of both worlds: separation where it matters, and simplicity where you want it.</p>
<h2><strong>The workspace layout</strong></h2>
<p>The sample project is structured like this:</p>
<pre><code class="language-plaintext">.
|-- package.json
|-- pnpm-workspace.yaml
|-- watt.json
`-- web
    |-- backend
    |   |-- medusa-config.ts
    |   |-- package.json
    |   |-- url-handler.js
    |   `-- watt.json
    |-- frontend
    |   |-- next.config.js
    |   |-- package.json
    |   |-- watt.image-optimizer.json
    |   |-- watt.json
    |   `-- src
    `-- gateway
        |-- package.json
        `-- watt.json
</code></pre>
<p>At the root, <code>watt.json</code> autoloads the <code>web/*</code> applications, sets <code>gateway</code> as the public entrypoint, and adds an extra application called <code>image-server</code> that reuses the frontend codebase with a different config.</p>
<p>This is where the monorepo model really shines. You can easily reuse the same codebase for different runtime roles. There’s no need to create a second Next.js project just to separate <code>/_next/image</code>. Instead, you keep one frontend codebase and let Watt run it in two different ways.</p>
<h2><strong>pnpm workspace setup: one dependency graph, fewer surprises</strong></h2>
<p>If you use pnpm, make the workspace explicit with <code>pnpm-workspace.yaml</code>:</p>
<pre><code class="language-plaintext">packages:
 - web/*
</code></pre>
<p>Then pin the React family at the root in <code>package.json</code>:</p>
<pre><code class="language-json">{
 "pnpm": {
   "overrides": {
     "react": "19.0.4",
     "react-dom": "19.0.4",
     "@types/react": "19.0.4",
     "@types/react-dom": "19.0.4"
   }
 }
}
</code></pre>
<p>This is a clear reason why using a monorepo matters. The Medusa storefront, Next.js, and related tools all rely on React. In a multi-repo setup, versions can easily get out of sync. With a Watt monorepo, you set the version once at the root, and every app benefits right away.</p>
<p>This makes building more predictable and keeps maintenance costs much lower.</p>
<h2><strong>One .env, clear public and internal boundaries</strong></h2>
<p>The root <code>.env</code> needs a few shared values:</p>
<ul>
<li><p><code>REDIS_HOST</code></p>
</li>
<li><p><code>MEDUSA_PUBLIC_BACKEND_URL</code></p>
</li>
<li><p><code>MEDUSA_BACKEND_URL</code></p>
</li>
</ul>
<p>The key distinction is this:</p>
<ul>
<li><p><code>MEDUSA_PUBLIC_BACKEND_URL</code> is for the externally visible backend URL</p>
</li>
<li><p><code>MEDUSA_BACKEND_URL</code> is for server-side calls from the frontend</p>
</li>
</ul>
<p>On ICC, this is the ideal setup:</p>
<pre><code class="language-plaintext">MEDUSA_PUBLIC_BACKEND_URL=https://medusa.plt/backend
MEDUSA_BACKEND_URL=http://backend.plt.local
</code></pre>
<p>Why it matters:</p>
<ul>
<li><p>browsers and the admin UI use the public backend URL</p>
</li>
<li><p>The frontend server uses <code>http://backend.plt.local</code> and stays on the Platformatic mesh.</p>
</li>
</ul>
<p>It’s worth emphasizing that second point, since it provides both great DevEx and a substantial performance boost. Thanks to Watt and inter-thread communication, server-side requests skip the public gateway and stay within the process’s internal network.</p>
<p>Once again, the monorepo helps here. The internal service name and public URL strategy are side-by-side in the same workspace, making them much harder to misconfigure.</p>
<h2><strong>Backend: run Medusa as a Watt application</strong></h2>
<p>In <code>web/backend/package.json</code>, add <code>@platformatic/node</code>:</p>
<pre><code class="language-json">{
 "dependencies": {
   "@platformatic/node": "^3.44.0"
 }
}
</code></pre>
<p>Then configure <code>web/backend/watt.json</code>:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/node/3.44.0.json",
 "application": {
   "basePath": "/backend",
   "commands": {
     "development": "npm run dev",
     "build": "npm run build",
     "production": "npm run start"
   },
   "changeDirectoryBeforeExecution": false,
   "entrypointPort": 3000
 },
 "node": {
   "disableBuildInDevelopment": true,
   "dispatchViaHttp": true,
   "absoluteUrl": true
 },
 "watch": false
}
</code></pre>
<p>This setup gives Medusa a clear application boundary within the workspace, while still allowing the gateway to publish it under <code>/backend</code>.</p>
<p>The companion change in <code>web/backend/medusa-config.ts</code> is just as important:</p>
<pre><code class="language-typescript">import { defineConfig, loadEnv } from '@medusajs/framework/utils'

loadEnv(process.env.NODE_ENV || 'development', process.cwd())

module.exports = defineConfig({
 projectConfig: {
   databaseUrl: process.env.DATABASE_URL,
   http: {
     storeCors: process.env.STORE_CORS!,
     adminCors: process.env.ADMIN_CORS!,
     authCors: process.env.AUTH_CORS!,
     jwtSecret: process.env.JWT_SECRET || 'supersecret',
     cookieSecret: process.env.COOKIE_SECRET || 'supersecret'
   },
   cookieOptions: {
     sameSite: 'lax',
     secure: false
   }
 },
 admin: {
   path: (new URL(process.env.MEDUSA_PUBLIC_BACKEND_URL!).pathname + '/app') as `/string`,
   backendUrl: process.env.MEDUSA_PUBLIC_BACKEND_URL,
   vite: config =&gt; {
     config.server.allowedHosts ??= []
     config.server.allowedHosts.push('.plt.local')
   }
 }
})
</code></pre>
<p>The admin path comes from the public backend URL. So, if ICC publishes the backend at <code>/backend</code>, the admin will automatically be available at <code>/backend/app</code>.</p>
<p>You should also keep <code>web/backend/url-handler.js</code> in place. Medusa’s API and admin UI do not behave identically when you put them behind a prefixed public path, so Watt’s gateway uses this file to rewrite requests correctly.</p>
<p>The implementation used in the sample project looks like this:</p>
<pre><code class="language-javascript">const basePath = process.env.PLT_BASE_PATH ?? ''
const adminPath = new URL(process.env.MEDUSA_PUBLIC_BACKEND_URL).pathname.replace(/\/$/, '')
const adminUiPath = adminPath + '/app'
const adminMatcher = new RegExp(`^${adminPath}`)

export default {
 preRewrite(url) {
   if (basePath &amp;&amp; !url.startsWith(basePath)) {
     url = `${basePath}${url}`
   }

   url = url.startsWith(adminUiPath) ? url : url.replace(adminMatcher, '')
   return url
 }
}
</code></pre>
<p>This file may be small, but it does important work. It keeps the admin UI path intact while removing the backend prefix for API routes that Medusa expects to serve from the root.</p>
<h2><strong>Frontend: one codebase, two runtime roles</strong></h2>
<p>In <code>web/frontend/package.json</code>, add <code>@platformatic/next</code>:</p>
<pre><code class="language-json">{
 "dependencies": {
   "@platformatic/next": "^3.44.0"
 }
}
</code></pre>
<p>The standard frontend config in <code>web/frontend/watt.json</code> is simple:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/next/3.44.0.json",
 "application": {
   "basePath": "{PLT_BASE_PATH}",
   "changeDirectoryBeforeExecution": true
 },
 "next": {
   "trailingSlash": true
 }
}
</code></pre>
<p>And in <code>web/frontend/next.config.js</code>, set:</p>
<pre><code class="language-javascript">const nextConfig = {
 reactStrictMode: true,
 logging: {
   fetches: {
     fullUrl: true
   }
 },
 eslint: {
   ignoreDuringBuilds: true
 },
 typescript: {
   ignoreBuildErrors: true
 }
}
</code></pre>
<p>Here’s where it gets interesting: the monorepo lets you reuse the same frontend codebase as a dedicated image optimization service, with almost no extra work.</p>
<h2><strong>Split image optimization without splitting the repo</strong></h2>
<p>We recently covered why this architecture matters in our post on <a href="https://blog.platformatic.dev/scale-nextjs-image-optimization-platformatic">scaling Next.js image optimization with a dedicated Platformatic application</a>: image optimization is CPU-heavy and can become a noisy neighbour for SSR traffic.</p>
<p>That is exactly why this Medusa setup runs <code>/_next/image</code> separately.</p>
<p>Create <code>web/frontend/watt.image-optimizer.json</code>:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/next/3.44.0.json",
 "logger": {
   "level": "trace"
 },
 "application": {
   "basePath": "/",
   "changeDirectoryBeforeExecution": true
 },
 "next": {
   "trailingSlash": true,
   "imageOptimizer": {
     "enabled": true,
     "fallback": "frontend",
     "timeout": 30000,
     "ttl": 3600000,
     "maxAttempts": 3,
     "storage": {
       "type": "valkey",
       "url": "{REDIS_HOST}"
     }
   }
 }
}
</code></pre>
<p>This is a great example of why Watt monorepos work so well.</p>
<ul>
<li><p>You reuse the same frontend app.</p>
</li>
<li><p>You keep one source tree.</p>
</li>
<li><p>You give it a second runtime role.</p>
</li>
<li><p>You isolate a CPU-heavy path without creating a second frontend project.</p>
</li>
</ul>
<p>This setup improves both maintainability and performance, which is exactly what you want from your platform architecture.</p>
<p>The <code>fallback: "frontend"</code> setting is especially nice here: relative image URLs are resolved through the main storefront service over the runtime network, so the optimizer stays tightly integrated without being coupled to the frontend worker pool.</p>
<h2><strong>Next.js build-time pragmatism: force dynamic where it helps</strong></h2>
<p>Because the Medusa backend is not available during the <code>wattpm build</code>, the storefront cannot pre-generate some pages safely.</p>
<p>For these files:</p>
<ul>
<li><p><code>web/frontend/src/app/[countryCode]/(main)/products/[handle]/page.tsx</code></p>
</li>
<li><p><code>web/frontend/src/app/[countryCode]/(main)/categories/[...category]/page.tsx</code></p>
</li>
<li><p><code>web/frontend/src/app/[countryCode]/(main)/collections/[handle]/page.tsx</code></p>
</li>
</ul>
<p>comment out <code>generateStaticParams</code> and add:</p>
<pre><code class="language-javascript">export const dynamic = 'force-dynamic'
</code></pre>
<p>This uses Next.js <a href="https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config">Route Segment Config</a> to force runtime rendering instead of static generation.</p>
<p>In a typical Next.js app, this might seem like a compromise. But in this setup, it’s the right choice. The storefront relies on live Medusa data, and Watt provides that backend at runtime.</p>
<p>This is another area where the monorepo helps. The build behaviour is clear because the backend and frontend are in the same workspace, and their dependencies are easy to see.</p>
<h2><strong>Gateway: one public surface for the whole stack</strong></h2>
<p>Add <code>@platformatic/gateway</code> in <code>web/gateway/package.json</code>:</p>
<pre><code class="language-json">{
 "dependencies": {
   "@platformatic/gateway": "^3.44.0"
 }
}
</code></pre>
<p>Then define <code>web/gateway/watt.json</code> like this:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/gateway/3.44.0.json",
 "gateway": {
   "applications": [
     {
       "id": "backend",
       "proxy": {
         "prefix": "/backend",
         "custom": {
           "path": "../backend/url-handler.js"
         }
       }
     },
     {
       "id": "frontend",
       "proxy": {
         "prefix": "/"
       }
     },
     {
       "id": "image-server",
       "proxy": {
         "prefix": "/",
         "routes": ["/_next/image", "/_next/image/*"],
         "methods": ["GET"]
       }
     }
   ]
 }
}
</code></pre>
<p>This is where the monorepo approach really starts to feel smooth and efficient.</p>
<ul>
<li><p><code>/backend</code> goes to Medusa</p>
</li>
<li><p><code>/</code> goes to the storefront</p>
</li>
<li><p><code>GET /_next/image</code> goes to the image optimizer</p>
</li>
</ul>
<p>Thanks to <code>@platformatic/gateway</code>, you get one public entry point, but the traffic still lands on the right internal application.</p>
<p>This setup is easier to understand, change, and scale than trying to connect separate services outside the repo.</p>
<h2><strong>A small middleware detail that improves the experience</strong></h2>
<p>There is another subtle optimization in the storefront middleware <code>(web/frontend/src/middleware.ts)</code>.</p>
<p>When the request already contains a country code in the URL but does not yet have the <code>medusacache_id</code> cookie, the middleware sets that cookie and returns <code>NextResponse.next()</code> instead of forcing another redirect.</p>
<p>It’s a small detail, but it’s the kind of optimization that’s easier to maintain in a monorepo. Storefront routing, Medusa region lookups, and platform-level caching thanks to Watt HTTP caching handling are all managed together.</p>
<p>In practice, this helps the storefront set up its region-aware state smoothly, without extra steps.</p>
<p>The change is small enough to think of as a focused patch:</p>
<pre><code class="language-typescript"> if (urlHasCountryCode &amp;&amp; !cacheIdCookie) {
+    const response = NextResponse.next()

   response.cookies.set('_medusa_cache_id', cacheId, {
     maxAge: 60 * 60 * 24
   })

   return response
 }
</code></pre>
<p>This is the kind of practical improvement that’s easier to maintain when routing logic, storefront behaviour, and platform deployment are all in the same repo.</p>
<h2><strong>ICC environment values</strong></h2>
<p>In <code>.env.icc</code>, the main settings to align are:</p>
<pre><code class="language-plaintext">MEDUSA_PUBLIC_BACKEND_URL=https://medusa.plt/backend
STORE_CORS=https://docs.medusajs.com,https://medusa.plt
ADMIN_CORS=https://docs.medusajs.com,https://medusa.plt
AUTH_CORS=https://docs.medusajs.com,https://medusa.plt
NEXT_PUBLIC_BASE_URL=https://medusa.plt
</code></pre>
<p>They all reflect the same core rule: the whole application is published under <code>/medusa</code>, so both Medusa and Next.js need to agree on that public shape.</p>
<p>Since these settings are in one workspace and one deployment artifact, keeping them in sync is much easier than with a split-repo setup.</p>
<h2><strong>The Docker build is simple because the repo is simple</strong></h2>
<p>The container image is straightforward:</p>
<pre><code class="language-plaintext">FROM node:22-alpine

# Environment setup
ENV APP_HOME=/home/app/node/
ENV PLT_BASE_PATH="/medusa"
ENV PLT_ICC_URL="http://icc.platformatic.svc.cluster.local"
WORKDIR $APP_HOME

# Install dependencies
RUN npm install -g pnpm wattpm-utils "@platformatic/watt-extra@latest"
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml $APP_HOME
RUN pnpm install --frozen-lockfile --node-linker=hoisted

# Copy application
COPY web $APP_HOME/web
COPY .env.icc watt.json $APP_HOME
RUN mv .env.icc .env
RUN pnpm run build

# Final setup
EXPOSE 3042
EXPOSE 9090
CMD ["watt-extra", "start"]
</code></pre>
<p>There are two details worth mentioning.</p>
<p>First, using <code>--node-linker=hoisted</code> with pnpm installs dependencies in a flatter layout, instead of the usual symlink-heavy structure. In a workspace with Medusa, Next.js, shared React versions, and several Watt apps, this makes module resolution more predictable and helps avoid compatibility issues during container builds.</p>
<p>Second, <code>@platformatic/watt-extra</code> is a helper CLI that starts Watt smoothly in container environments like ICC. It adds the operational support you need at runtime, so your container entrypoint remains simple.</p>
<p>This is another area where the monorepo pays off right away: you have one install step, one build step, and one runtime command.</p>
<h2><strong>Why does this feel better to maintain</strong></h2>
<p>The main advantage of this Medusa setup isn’t any single config file. It’s the overall structure:</p>
<ul>
<li><p>One repo for backend, frontend, gateway, and optimizer</p>
</li>
<li><p>One dependency strategy</p>
</li>
<li><p>One place to define public and internal URLs</p>
</li>
<li><p>One deployment artifact for Kubernetes and ICC</p>
</li>
<li><p>One runtime that still preserves application boundaries</p>
</li>
</ul>
<p>Since Watt sees the platform as a group of coordinated apps, you can make performance improvements without making the system harder to manage.</p>
<p>You can send image optimization to a dedicated service, keep frontend-to-backend calls on the mesh network, mount everything under a base path, and update all these rules in one place.</p>
<p>That’s the real value of running Medusa in a Watt monorepo on ICC: convenience and performance work together, instead of getting in each other’s way. Because ICC provides a <strong>Kubernetes (K8S)</strong>-native environment, your monorepo and its services benefit from K8s's inherent scalability, resilience, and orchestration capabilities. This integration ensures that deploying and managing Medusa within the Watt monorepo is seamless, leveraging the enterprise-grade infrastructure of ICC (which is built on K8S) for optimal operational efficiency.</p>
<p>If you’re building commerce systems with lots of moving parts, this is the kind of platform setup you want.</p>
]]></content:encoded></item><item><title><![CDATA[Agents in Production: Reliable Orchestration and Security Enforcement on Kubernetes]]></title><description><![CDATA[Learn how to run AI agents reliably and securely on Kubernetes with Regina Coordinator for stateful orchestration & eBPF Sandbox for runtime security]]></description><link>https://blog.platformatic.dev/agents-in-production-reliable-orchestration-and-security-enforcement-on-kubernetes</link><guid isPermaLink="true">https://blog.platformatic.dev/agents-in-production-reliable-orchestration-and-security-enforcement-on-kubernetes</guid><category><![CDATA[AI]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Security]]></category><category><![CDATA[eBPF]]></category><category><![CDATA[platformatic]]></category><dc:creator><![CDATA[Luca Maraschi]]></dc:creator><pubDate>Thu, 16 Apr 2026 14:35:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/1c2b21ce-8d9b-465d-853f-d1e8fcb20a4c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>AI agents are moving beyond demos and into real production use. In production, you need sessions that last through infrastructure changes, code that stays secure, and controls that your platform team can enforce.</p>
<p>Today, we’re launching two tools to meet these needs. <strong>Regina Coordinator</strong> handles stateful agent routing and recovery on Kubernetes. <strong>eBPF Sandbox</strong> enforces security policies for agent-generated code at the process level. Both run together inside Watt and answer the two main questions we hear from infrastructure teams: How can <em>we run agents reliably at scale?</em> And <em>how can we do it without creating security risks?</em></p>
<hr />
<h2><strong>Part 1: Regina Coordinator. Stateful Sessions on Ephemeral Infrastructure</strong></h2>
<h3>The problem</h3>
<p>When an AI agent manages a multi-turn conversation, it builds up state like conversation history, tool outputs, and files created during the session. This state exists in a specific process on a specific pod. Kubernetes is designed for stateless workloads and doesn’t guarantee pods will last, which doesn’t match how agents work.</p>
<p>​If nothing manages this, a pod eviction or rolling deployment means a lost session. A crash at 2 am becomes a support ticket by morning. For agents used in product workflows, these problems aren’t acceptable.</p>
<p>​The <strong>Regina Coordinator</strong> solves this problem. It sits in front of your Regina pods and manages the whole session lifecycle: routing, failure detection, backup, and recovery. Pod restarts, rolling deployments, and crashes are hidden from users. Sessions keep going without interruption.</p>
<h3>Why stateful?</h3>
<p>Some agent frameworks use a stateless approach. They store all session state in a database, make each request independent, and let any instance handle any request. This works well for simple request-response agents and is easy to manage.</p>
<p>Regina uses a stateful model because agents that run code build up real in-process state over time. An agent that writes and runs code, installs packages, keeps tool connections open, and uses a virtual filesystem is doing work that builds on itself, not just sending messages to a database. Saving and restoring this environment for every message is too costly or limiting. For these agents, the virtual filesystem is the main workspace.</p>
<p>The tradeoff is more operational complexity: stateful sessions need routing, failure recovery, and backup. That’s what the Coordinator is for. The goal is to make stateful sessions work on stateless infrastructure, without putting the burden on application developers.</p>
<h3><strong>Architecture</strong></h3>
<p>Regina runs inside <a href="https://docs.platformatic.dev/docs/Overview">Watt</a>, Platformatic’s Node.js application server. Watt manages multiple services in one process and handles their lifecycle and communication. Regina builds on this to support stateful agent instances.</p>
<p>The system has three main services:</p>
<ul>
<li><p><strong>Regina</strong> manages agent definitions, creates and manages agent instances, and handles their lifecycle, including suspension, backup, and restore.</p>
</li>
<li><p><strong>Regina Agent</strong> is the runtime for each agent. Each instance runs in its own thread with its own AI model connection, tools, and virtual filesystem.</p>
</li>
<li><p><strong>Regina Coordinator</strong> acts as the gateway. It routes requests to the right pod and manages failure recovery across the cluster.</p>
</li>
</ul>
<h3>Deployment</h3>
<p>One coordinator manages a group of Regina pods. It runs as a standard Kubernetes service and is the entry point for all client traffic. Regina pods run as a headless service without a load balancer, so the coordinator connects to them directly using their pod IPs.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/58e45fa1-213d-4987-a38a-81cfbfa9eaac.png" alt="" style="display:block;margin:0 auto" />

<p>When a Regina pod starts, it registers itself in Redis with its address, instance count, and a 30-second TTL. It refreshes this TTL every 10 seconds. If a pod stops sending heartbeats, because it crashed, was evicted, or lost network connectivity, its keys expire after 30 seconds, and the coordinator stops routing to it. The failure detection window is automatic and limited.</p>
<h3>Session lifecycle</h3>
<p>When a user starts a new chat, the coordinator picks a pod using one of three allocation strategies:</p>
<ul>
<li><p><strong>Round-robin</strong> cycles through pods in order.</p>
</li>
<li><p><strong>Least-loaded</strong> picks the pod with the fewest active instances.</p>
</li>
<li><p><strong>Random</strong> picks a pod at random.</p>
</li>
</ul>
<p>On the chosen pod, Regina creates a new agent instance in its own thread with its own model connection, tools, and virtual filesystem. The instance registers itself in the session store so the coordinator can route all future messages to it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/85c503e6-d9ce-4249-b5b1-c52655e7f6c9.png" alt="" style="display:block;margin:0 auto" />

<p>Every message from the user goes through the coordinator, which checks the session store, forwards it to the right pod, and returns the response. For the user, it feels like one continuous conversation, no matter what happens behind the scenes.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/624cccca-42da-446f-a574-465f796d46e4.png" alt="" style="display:block;margin:0 auto" />

<h3>Keeping sessions alive</h3>
<p>An agent instance might stop because of a pod crash, a rolling deployment, or idle suspension to save resources. In every case, the conversation needs to be saved. Regina does this by backing up each instance’s virtual filesystem to shared storage. Three backends are supported:</p>
<ul>
<li><p><strong>S3</strong> for production deployments, also compatible with MinIO and Cloudflare R2</p>
</li>
<li><p><strong>Redis</strong> for smaller deployments, storing the filesystem as a hash entry</p>
</li>
<li><p><strong>Filesystem</strong> for shared volumes like NFS or EFS</p>
</li>
</ul>
<p><strong>Idle suspension</strong>: If no messages come in for five minutes, Regina backs up the virtual filesystem and stops the agent thread. When a new message arrives, the coordinator sends it to the same pod. Regina notices the instance is suspended, restores the backup, restarts the thread, and the conversation continues right where it left off.</p>
<p><strong>Graceful shutdown</strong>: During rolling deployments or scale-downs, Regina backs up all active instances before the pod shuts down. Nothing is lost.</p>
<p><strong>Crash recovery</strong>: If a pod crashes without a graceful shutdown, only the last backup is available. After 30 seconds, the pod’s keys expire in Redis, and the coordinator finds the orphaned session: the instance mapping is there, but the pod is gone. The coordinator picks a healthy pod, forwards the request, and Regina restores the virtual filesystem from shared storage and restarts the agent thread. The conversation continues on the new pod without any interruption for the user.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/dda4c7e9-cff4-42b2-99ff-9aebc505d099.png" alt="" style="display:block;margin:0 auto" />

<h3>API</h3>
<p>The coordinator provides a REST API for agent discovery, session management, and chat.</p>
<p><strong>Agent discovery</strong> gathers definitions from all registered pods and returns a deduplicated list, so clients always know which agents are available across the cluster.</p>
<p><strong>Session management</strong> includes creating, deleting, and listing instances. New instances are placed using the chosen allocation strategy. Listing shows instances across all pods for a given agent definition.</p>
<p><strong>Chat</strong> supports two modes: synchronous, which returns a single JSON response, and streaming, which delivers tokens as NDJSON. In streaming mode, the coordinator passes the response directly from the pod without buffering.</p>
<hr />
<h2><strong>Part 2: eBPF Sandbox. Security Enforcement for Agent-Generated Code</strong></h2>
<h3><strong>The problem</strong></h3>
<p>Reliability is only half of what’s needed in production. The other half is security.</p>
<p>An agent that can run arbitrary code, install packages, execute shell commands, and call external APIs is like running untrusted software on your infrastructure. The code is generated at runtime, changes with every request, and the agent decides what to run on its own. For many teams, this real security risk keeps agents in demo environments instead of production, because existing controls weren’t built for this: cgroups, and network controls at the CNI or service-mesh layer. These matters, but agent workloads need a different control model. The key difference is that agents are <strong>processes with changing intent</strong>, not static applications with known behaviour at deploy time. Standard controls assume you know what the process will do when you deploy it. Agents don't have that property.</p>
<p>The requirements are specific: only certain outbound destinations should be allowed, only certain binaries should run after startup, resource limits should apply to each agent process, and policies need to be able to tighten while the process is running, not just at container start.</p>
<p>That’s exactly what eBPF Sandbox is designed to handle.</p>
<h3>What it does</h3>
<p>eBPF Sandbox is a Linux tool for isolating processes. It uses Linux namespaces for user, mount, and PID isolation, cgroups for resource limits, eBPF hooks for runtime policy enforcement, and seccomp to block critical syscalls. A small client/server control plane sets up and activates each sandbox.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/63bfdd8b-4f2a-4008-86fd-c86bdd682bca.png" alt="" style="display:block;margin:0 auto" />

<p>The main reason to use eBPF is that it enforces policy directly in the kernel, not through a wrapper library, special runtime, or sidecar. Once the sandbox is active, the same boundaries apply to the whole process tree, including any child processes started by agent-generated code.</p>
<p>​The system has two parts: a <strong>client-side launcher</strong> that prepares and starts sandboxed processes, and a <strong>server-side daemon</strong> that manages cgroups, loads eBPF programs, and activates policies.</p>
<p>Namespaces control what the process can see. Cgroups control what it can use. eBPF and seccomp control what it can do.</p>
<h3>A policy example</h3>
<p>A sandbox policy brings together process, network, and resource controls in one definition. The main question it answers is: what should this process be allowed to see, use, run, and access?</p>
<pre><code class="language-json">{
 "presets": ["posix-ro", "node"],
 "network": {
   "rules": [
     { "action": "deny", "destination": "169.254.169.254", "note": "block metadata service" },
     { "action": "allow", "destination": "*.anthropic.com", "port": 443 },
     { "action": "allow", "destination": "10.0.0.0/8" }
   ]
 },
 "resources": {
   "memoryLimit": "1G",
   "cpuLimit": "50000 100000"
 }
}
</code></pre>
<p>This policy lets the sandbox call a specific external API over HTTPS, reach internal services on the private network, block access to the instance metadata service, use an approved runtime and a minimal set of POSIX tools, and stay within set resource <code>limits.ts.</code></p>
<p>Presets like <code>posix-ro</code> and <code>node</code> are bundles of common permissions, so you don’t need long binary allowlists. They make policies easier to read and reuse across agent definitions.</p>
<p>**No pre-enforcement execution window<br />**The most important security feature is sequencing. A naive approach starts the process, moves it into the right cgroup, attaches enforcement, and hopes nothing happens in the gap. Even a small timing window lets a process open a socket, fork a child, or act outside the intended <code>limits.ry</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/6b6bd3f5-6215-45d7-b3b1-5621a6b90558.png" alt="" style="display:block;margin:0 auto" />

<p>eBPF Sandbox removes this timing window completely. Enforcement is active before the sandboxed command runs its first instruction. The isolated filesystem is ready before the process starts, so there’s no unprotected startup phase.</p>
<h3><strong>The runtime view</strong></h3>
<p>To the process, the sandbox looks like a minimal runtime environment, not a full container image or host. It provides:</p>
<ul>
<li><p><code>/workspace</code> as its writable working directory</p>
</li>
<li><p><code>/usr</code>, <code>/lib</code>, and <code>/lib64</code> as read-only runtime dependencies</p>
</li>
<li><p><code>/bin</code> and <code>/sbin</code> as read-only entry points</p>
</li>
<li><p>A minimal <code>/etc</code> for name resolution and basic user lookups</p>
</li>
<li><p><code>/proc</code> for process introspection</p>
</li>
<li><p><code>/tmp</code> as a private tmpfs</p>
</li>
</ul>
<p>You can expose extra host paths as read-only mounts if a workload needs access to certain data or configuration. The idea is to expose only what the process really needs, and only as read-only whenever possible.</p>
<h3><strong>Network policy</strong></h3>
<p>The network model works like security group rules, but applied at the process level instead of the container or pod level.</p>
<p>IP and CIDR rules handle the straightforward cases: blocking the metadata service, allowing RFC1918 ranges, or denying all outbound except specific destinations.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/d2ad5996-14f6-47ea-bf0c-231b45ecfea1.png" alt="" style="display:block;margin:0 auto" />

<p>Hostname rules are more useful for agent workloads. The kernel doesn’t see "connect to api.example.com”, it sees "connect to this IP." For TLS traffic, the sandbox checks the hostname during the TLS Server Name Indication handshake. This makes policies like <code>allowing *.anthropic.com</code> and <code>denying everything else</code> accurate and reliable.</p>
<p>This matters because many services are behind shared infrastructure like CDNs, cloud load balancers, and anycast front doors. At the IP level, different hostnames look the same. TLS hostname inspection lets you write policies based on the services you actually want to allow, which is usually what teams mean by network policy. Policy is treated as data, not something fixed at process startup. The daemon writes policy into the kernel, and changes can take effect without restarting the sandboxed process.​</p>
<p>This is important for agent workflows where permissions need to change during a session. For example, you might allow a package download during setup, remove that access once the environment is ready, or temporarily allow an internal service for a specific step, then revoke it. Static policy at container start can’t handle this, but live policy updates can.​</p>
<p>The system also supports a global policy ceiling. The platform team sets the outer boundary once, and individual sandbox policies can be more restrictive but never more permissive. Application teams can narrow the boundary for their workloads, but can’t go beyond the platform limit.</p>
<h3>Kubernetes deployment</h3>
<p>In Kubernetes, the sandbox daemon runs as a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/">DaemonSet</a>: one daemon per node. This setup works because the daemon needs direct node access to manage host processes, create and manage cgroups, and load and maintain eBPF programs and maps. The DaemonSet pattern gives it that access without needing privileged containers for the agent workloads.</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/ae64bf8e-9b27-4146-a412-f816ec1aecfe.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Why do these two components belong together?</h2>
<p>Reliability and security go hand in hand. An agent system that recovers from pod failures but runs code without enforcement isn’t ready for production. A system with strong sandboxing but weak session routing creates other operational problems.</p>
<p>Regina Coordinator and eBPF Sandbox are built to work together in production. The coordinator keeps agent sessions running through the infrastructure events that always happen on Kubernetes. The sandbox makes sure the code those agents run is safe on your own infrastructure.</p>
<p>Both tools run inside Watt. There are no managed service tradeoffs, no black-box runtime, and no vendor lock-in for your execution environment. You keep control of your infrastructure, and these components help make that control practical.</p>
<p>For more details on how agent instances work, including definitions, tools, the AI loop, and session persistence, see <a href="https://blog.platformatic.dev/introducing-regina-stateful-ai-agent-orchestration-watt">the companion article</a>. Documentation for both components is at <a href="https://docs.platformatic.dev">docs.platformatic.dev</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Introducing Regina: Stateful AI Agent Orchestration for Platformatic Watt]]></title><description><![CDATA[Regina: a stateful AI agent orchestration layer for Platformatic Watt, enabling scalable, persistent, and production-ready agent workflows.]]></description><link>https://blog.platformatic.dev/introducing-regina-stateful-ai-agent-orchestration-watt</link><guid isPermaLink="true">https://blog.platformatic.dev/introducing-regina-stateful-ai-agent-orchestration-watt</guid><category><![CDATA[AI]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[platformatic]]></category><dc:creator><![CDATA[Paolo Insogna]]></dc:creator><pubDate>Tue, 14 Apr 2026 14:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/b492a6aa-6050-460c-be39-465c2c437bad.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We’re excited to share Regina, a production-ready agent orchestration layer built on <a href="https://docs.platformatic.dev/">Platformatic Watt</a>.</p>
<p>Regina lets you go from single-agent demos to real systems you can run and scale confidently. You define agents in Markdown, start instances over HTTP, and get built-in lifecycle management, persistence, and recovery, all by running and managing agents in Watt as isolated worker threads.</p>
<h2>Why Regina, why now</h2>
<p>Most AI projects hit the same wall after the first demo:</p>
<ul>
<li><p>Prompts are not versioned in a clean, operational way.</p>
</li>
<li><p>Sessions disappear on restart.</p>
</li>
<li><p>Scaling introduces routing and state headaches.</p>
</li>
<li><p>Tool-heavy workflows are hard to observe and control.</p>
</li>
</ul>
<p>Regina solves these problems directly, so your team can focus on building your product and not re-inventing the wheel when it comes to complex orchestration and state management.</p>
<h2>What you get on day one</h2>
<p>Regina comes as three packages:</p>
<ul>
<li><p><code>@platformatic/regina</code>: per-pod agent manager</p>
</li>
<li><p><code>@platformatic/regina-agent</code>: per-agent runtime</p>
</li>
<li><p><code>@platformatic/regina-storage</code>: pluggable backup adapters (<code>fs, s3, redis</code>)</p>
</li>
</ul>
<p>With this stack, you’ll have:</p>
<ul>
<li><p>stateful agent instances with per-instance SQLite VFS <em>(“Virtual File System”)</em></p>
</li>
<li><p>suspend/resume lifecycle management with idle timeout control</p>
</li>
<li><p>NDJSON streaming events for full run visibility</p>
</li>
<li><p>steerable agentic loops via <code>POST /instances/:id/steer</code></p>
</li>
<li><p>storage-backed restore for resilient multi-pod operation</p>
</li>
</ul>
<h2><strong>Markdown-native agent definitions</strong></h2>
<p>Regina uses Markdown with YAML frontmatter as the main source for each agent.</p>
<pre><code class="language-plaintext">---
name: support-agent
description: Customer support assistant
model: anthropic/claude-sonnet-4-5
provider: vercel-gateway
tools:
 - ./tools/search-docs.ts
temperature: 0.3
maxSteps: 10
---
You are a helpful support agent.
</code></pre>
<p>This setup keeps prompt and runtime configuration together, so it’s easy to review in pull requests and update across teams.</p>
<h2><strong>Built for real runtime behaviour</strong></h2>
<p>Regina keeps management and execution separate:</p>
<ul>
<li><p><code>@platformatic/regina</code> discovers definitions, spawns instances, and proxies instance APIs</p>
</li>
<li><p><code>@platformatic/regina-agent</code> runs each instance in isolation</p>
</li>
<li><p>message history is persisted at <code>/.session/messages.jsonl</code> in each instance VFS</p>
</li>
</ul>
<p>This design gives you reliable performance, even under heavy load:</p>
<ul>
<li><p><strong>Idle suspension</strong> to free resources automatically</p>
</li>
<li><p><strong>Auto-resume</strong> on next request</p>
</li>
<li><p><strong>State continuity</strong> across restarts</p>
</li>
<li><p><strong>Rich streaming</strong> <code>(text-delta, tool-call, tool-result, step-finish</code>)</p>
</li>
</ul>
<p>In practice, running your agents with Regina and Watt gives you agents that act like durable workflows backed by persistent state instead of ephemeral, one-off chat sessions.</p>
<h2><strong>Start simple and scale smoothly</strong></h2>
<p>Regina works great in single-pod mode with no Redis, no external storage, and minimal setup.</p>
<p>As your traffic grows, you can add Redis or Valkey for member and instance mapping, and add shared storage for state restore if needed. The API stays the same, so clients don’t need to change as your setup evolves.</p>
<h2><strong>Getting started</strong></h2>
<p>The Regina demo app is small on purpose, but it shows the full production pattern in a single repo:</p>
<ul>
<li><p><code>watt.json</code> at the root defines a single entrypoint service for Regina</p>
</li>
<li><p><code>services/regina/watt.json</code> enables <code>@platformatic/regina</code> and points to the shared <code>agents/</code> directory</p>
</li>
<li><p>Each file in <code>agents/</code> is a full agent definition <em>(prompt + model + provider + tools)</em></p>
</li>
<li><p>Custom tools sit alongside agents in <code>agents/tools/*</code></p>
</li>
</ul>
<p>Here’s how the demo app is set up.</p>
<p>Root <code>watt.json</code>:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/wattpm/3.50.0.json",
 "server": {
   "port": 3042
 },
 "management": true,
 "entrypoint": "regina",
 "services": [
   {
     "id": "regina",
     "path": "./services/regina",
     "management": {
       "operations": ["addApplications", "removeApplications", "getApplications", "getApplicationDetails", "inject"]
     }
   }
 ]
}
</code></pre>
<p>Service <code>services/regina/watt.json</code>:</p>
<pre><code class="language-json">{
 "$schema": "https://schemas.platformatic.dev/@platformatic/regina/0.1.0.json",
 "regina": {
   "agentsDir": "../../agents"
 }
}
</code></pre>
<p>Example agent definition (<code>agents/assistant.md</code>):</p>
<pre><code class="language-plaintext">---
name: assistant
description: A general-purpose assistant with file and shell access
model: anthropic/claude-sonnet-4-5
provider: vercel-gateway
greeting: "Hi! I'm a general-purpose assistant. I can read and write files, run commands, and help with any task."
temperature: 0.3
maxSteps: 15
---
You are a helpful assistant. You can read, write, and edit files, run bash commands, and help with any task.
</code></pre>
<p>Here’s a typical flow in the demo:</p>
<ol>
<li><p>Start Watt (<code>wattpm start</code>).</p>
</li>
<li><p>Create an instance from an agent definition (<code>POST /agents/:defId/instances</code>).</p>
</li>
<li><p>Chat with that instance (<code>POST /instances/:instanceId/chat or /chat/stream</code>).</p>
</li>
<li><p>Resume the same instance later with history already available.</p>
</li>
</ol>
<p>This is important because it shows Regina’s core value from start to finish: agents are defined as code, run as managed instances, and keep their state across requests without extra orchestration work.</p>
<h2><strong>Storage options for state backup</strong></h2>
<p>For multi-pod setups, configure <a href="http://regina.storage">regina.storage</a> so you can restore on another pod.</p>
<p><strong>Filesystem (</strong><code>fs</code><strong>)</strong></p>
<pre><code class="language-json">{
 "module": "@platformatic/regina",
 "regina": {
   "storage": {
     "type": "fs",
     "basePath": "/mnt/shared/regina-state"
   }
 }
}
</code></pre>
<p><strong>Object storage (</strong><code>s3</code><strong>)</strong></p>
<pre><code class="language-json">{
 "module": "@platformatic/regina",
 "regina": {
   "storage": {
     "type": "s3",
     "bucket": "regina-state",
     "prefix": "backups/",
     "endpoint": "https://s3.amazonaws.com"
   }
 }
}
</code></pre>
<p><strong>Redis (</strong><code>redis</code><strong>)</strong></p>
<pre><code class="language-json">{
 "module": "@platformatic/regina",
 "regina": {
   "redis": "redis://valkey:6379",
   "storage": {
     "type": "redis"
   }
 }
}
</code></pre>
<p>All adapters use the same interface (<code>put, get, delete, list, close</code>), so you can switch backends without changing how your clients work.</p>
<h2><strong>Get started</strong></h2>
<ul>
<li><p><a href="https://github.com/platformatic/regina">Regina repository</a></p>
</li>
<li><p><a href="https://github.com/platformatic/regina/tree/main/packages/regina">Regina package docs</a></p>
</li>
<li><p><a href="https://github.com/platformatic/regina/tree/main/packages/regina-agent">Agent runtime docs</a></p>
</li>
<li><p><a href="https://github.com/platformatic/regina/tree/main/packages/regina-storage">Storage adapters docs</a></p>
</li>
</ul>
<p>Regina is built for teams shipping serious AI systems on Node.js. If you need agents that are reliable, observable, and stateful in production, Regina is ready for you.</p>
]]></content:encoded></item><item><title><![CDATA[@platformatic/kafka Now Supports Confluent Schema Registry ]]></title><description><![CDATA[@platformatic/kafka v1.27.0 introduces built-in Confluent Schema Registry support for AVRO, Protobuf, and JSON Schema.]]></description><link>https://blog.platformatic.dev/platformatic-kafka-confluent-schema-registry-support</link><guid isPermaLink="true">https://blog.platformatic.dev/platformatic-kafka-confluent-schema-registry-support</guid><category><![CDATA[kafka]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Devops]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[Paolo Insogna]]></dc:creator><pubDate>Tue, 07 Apr 2026 14:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/ef50f002-fb0e-47aa-aeac-23d7be4891f5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you run Kafka in production, you can’t skip schema evolution. Teams need clear data types, compatibility checks, and a safe way to update contracts without breaking consumers or downstream services.</p>
<p>Before now, using <code>@platformatic/kafka</code> with Confluent Schema Registry meant writing extra code to connect the pieces. With <code>@platformatic/kafka</code> <strong>v1.27.0</strong>, that’s no longer needed.</p>
<p><code>@platformatic/kafka</code> now has built-in support for Confluent Schema Registry, including:</p>
<ul>
<li><p>AVRO</p>
</li>
<li><p>Protocol Buffers</p>
</li>
<li><p>JSON Schema</p>
</li>
<li><p>Basic and Bearer authentication</p>
</li>
<li><p>Automatic schema fetch and caching</p>
</li>
<li><p>Integrated Producer and Consumer hooks</p>
</li>
</ul>
<p>You get schema-aware messaging, and the project still focuses on being fast and predictable for Node.js Kafka clients.</p>
<h2><strong>Why This Matters</strong></h2>
<p>Most schema registry integrations add complexity where you don’t want it: in the message serialization and deserialization paths. Fetching remote schemas is asynchronous, but encoding and decoding should stay synchronous for speed and consistency.</p>
<p>Put simply, network I/O and cache coordination should happen before the main data processing, not during it. Keeping these steps separate helps maintain stable throughput and latency as traffic increases.</p>
<p>This release introduces a two-layer architecture to keep that separation clear:</p>
<ol>
<li><p><strong>Low-level hooks</strong> for async pre-processing:</p>
<ul>
<li><p><a href="https://github.com/platformatic/kafka/blob/main/docs/producer.md">beforeSerialization</a></p>
</li>
<li><p><a href="https://github.com/platformatic/kafka/blob/main/docs/consumer.md">beforeDeserialization</a></p>
</li>
</ul>
</li>
<li><p><strong>High-level registry API</strong> via <a href="https://github.com/platformatic/kafka/blob/main/docs/confluent-schema-registry.md">ConfluentSchemaRegistry</a></p>
</li>
</ol>
<p>In practice, this means schemas are fetched and cached before encode/decode happens, so your serializers and deserializers stay synchronous when messages are processed.</p>
<p>This gives application teams a simpler way to think about things: do the asynchronous prep first, then keep codec behavior predictable during main processing.</p>
<p>At a high level, the flow is:</p>
<ul>
<li><p>Extract schema ID from message metadata (producer) or wire payload (consumer).</p>
</li>
<li><p>Resolve schema from local cache when available.</p>
</li>
<li><p>On cache miss, fetch asynchronously via <code>beforeSerialization/beforeDeserialization</code> hooks and cache the schema.</p>
</li>
<li><p>Run synchronous serialization/deserialization with the resolved schema.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/043ca54f-3808-4811-8e47-b772feb30666.png" alt="" style="display:block;margin:0 auto" />

<p>In multi-instance deployments, that cache layer can be backed by Redis or Valkey, so workers share schema state across nodes while keeping encode/decode synchronous in the hot path.</p>
<h2><strong>What You Can Do Now</strong></h2>
<p>You can connect a registry directly to both the Producer and Consumer, letting <code>@platformatic/kafka</code> handle schema-aware serialization from start to finish.</p>
<p>This is especially helpful when several services publish and consume the same topics on different deployment cycles, since consistent schema handling is a must.</p>
<pre><code class="language-javascript">import { Consumer, Producer } from '@platformatic/kafka'
import { ConfluentSchemaRegistry } from '@platformatic/kafka/registries'

const registry = new ConfluentSchemaRegistry({
  url: 'http://localhost:8081'
})

const producer = new Producer({
  clientId: 'orders-producer',
  bootstrapBrokers: ['localhost:9092'],
  registry
})

const consumer = new Consumer({
  groupId: 'orders-consumers',
  clientId: 'orders-consumer',
  bootstrapBrokers: ['localhost:9092'],
  registry
})
</code></pre>
<p>When producing, pass schema IDs in message metadata:</p>
<pre><code class="language-javascript">await producer.send({
  messages: [
    {
      topic: 'orders',
      key: { orderId: 101 },
      value: { customerId: 'cust-44', total: 129.99 },
      metadata: {
        schemas: {
          key: 10,
          value: 11
        }
      }
    }
  ]
})
</code></pre>
<p>When consuming, payloads are automatically decoded with the cached schema. If a schema isn’t found, the registry fetches it before deserialization continues.</p>
<p>This makes it easy to move from custom codec code to a single registry integration in your client setup.</p>
<h2><strong>Authentication and Enterprise Scenarios</strong></h2>
<p>Schema Registry deployments are often protected. The new integration includes:</p>
<ul>
<li><p>Basic auth (<code>username</code> + <code>password</code>)</p>
</li>
<li><p>Bearer token auth (<code>token</code>)</p>
</li>
<li><p>Dynamic credentials via providers</p>
</li>
</ul>
<p>This makes it easier to connect to managed or secured registry instances without writing custom transport code. It also makes credential rotation simpler when you use providers.</p>
<p>If your setup uses short-lived credentials, provider functions let you refresh tokens and secrets without having to rebuild your producer or consumer logic.</p>
<h2><strong>Performance and Reliability Considerations</strong></h2>
<p>One main design goal was to avoid unnecessary overhead to message processing.</p>
<p>The implementation focuses on cache locality and step-by-step pre-processing:</p>
<ul>
<li><p>Schema IDs are extracted from the wire format <em>(or message metadata).</em></p>
</li>
<li><p>Unknown schemas are fetched once and cached.</p>
</li>
<li><p>Repeated schema IDs in a batch are resolved from the cache.</p>
</li>
<li><p>Encode/decode continues in synchronous paths.</p>
</li>
</ul>
<p>This setup cuts down on unnecessary async work while still supporting remote schema registries safely. It also helps keep throughput and performance steady, as you’d expect from a Node.js client.</p>
<p>Operationally, this also makes failures easier to understand. Schema resolution errors happen during fetch or preparation, while codec errors are still linked to payload and schema compatibility.</p>
<h2><strong>Also Included in This Release</strong></h2>
<p>The v1.27.0 release also shipped quality improvements around consumer behaviour and protocol handling, with broad test coverage and new playground clients for:</p>
<ul>
<li><p>AVRO</p>
</li>
<li><p>Protobuf</p>
</li>
<li><p>JSON Schema</p>
</li>
<li><p>Authenticated Schema Registry setups</p>
</li>
</ul>
<p>The end result is a production-ready integration you can try out quickly, starting in local development and moving to secure production registries.</p>
<h2><strong>Experimental API Notice</strong></h2>
<p><code>ConfluentSchemaRegistry</code> and its related hooks are currently <strong>experimental</strong>. They may change in minor or patch releases as we keep improving them based on real-world use and feedback.</p>
<p>If you plan to use this in production, make sure to pin your versions and check the release notes. We’ll keep refining the API based on feedback from real deployments.</p>
<p>If your team is rolling this out, here’s a practical way to start:</p>
<ol>
<li><p>Start with one topic and one schema format <em>(typically AVRO or JSON Schema)</em></p>
</li>
<li><p>Validate serialization/deserialization behaviour in staging with real payloads.</p>
</li>
<li><p>Expand topic coverage and introduce auth/credential providers as needed.</p>
</li>
</ol>
<h2><strong>Getting Started</strong></h2>
<p>Install the package:</p>
<pre><code class="language-plaintext">npm install @platformatic/kafka
</code></pre>
<p>For Protobuf support, also install:</p>
<pre><code class="language-plaintext">npm install protobufjs
</code></pre>
<p>Next, follow the full integration guide in the documentation:</p>
<ul>
<li><p><a href="https://github.com/platformatic/kafka/blob/main/docs/confluent-schema-registry.md">Confluent Schema Registry docs</a></p>
</li>
<li><p><a href="https://github.com/platformatic/kafka/releases/tag/v1.27.0">v1.27.0 release notes</a></p>
</li>
</ul>
<p>If you give it a try, we’d love to hear your feedback at <a href="mailto:hello@platformatic.dev">hello@platformatic.dev</a>. Real-world schema workflows will help shape the next version of this API and guide our priorities for future improvements.</p>
<p>Thanks for building with us! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[SSR Framework Benchmarks v2: What We Got Wrong, and the Real Numbers]]></title><description><![CDATA[Updated SSR benchmark results after fixing compression inconsistencies. See how TanStack, React Router, and Next.js perform at 1,000 req/s]]></description><link>https://blog.platformatic.dev/ssr-framework-benchmarks-v2-corrected-results</link><guid isPermaLink="true">https://blog.platformatic.dev/ssr-framework-benchmarks-v2-corrected-results</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Matteo Collina]]></dc:creator><pubDate>Tue, 24 Mar 2026 14:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/a6bfaa4d-f9dd-406f-8199-de4c38ac1824.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>TL;DR</h3>
<p>We ran our SSR framework benchmarks again after finding out that <strong>compression was not applied the same way across all frameworks</strong>. In the original tests, TanStack did not have compression enabled. React Router had gzip compression turned on in its Express <code>server.js</code>, but Watt skips <code>server.js</code> and uses Fastify. Because of this, React Router’s Watt runs had no compression overhead, while its Node and PM2 runs did. This made Watt seem faster than it actually was compared to the other runtimes.</p>
<p>Once we removed compression from React Router to make the comparison fair, the updated results gave us a clearer picture:</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/47b441d2-c720-45dc-938c-b6dccc5fbbb7.png" alt="" style="display:block;margin:0 auto" />

<p>TanStack and React Router are still the top performers, while Next.js continues to have trouble at 1,000 requests per second. The main change is that Watt’s advantage now appears mostly in tail latencies, with p(99) at 83-89ms compared to Node’s 121-298ms, instead of average response times.</p>
<hr />
<h2>What Went Wrong in the Previous Benchmarks</h2>
<p>HTTP compression means shrinking the response body before sending it over the wire, usually with gzip or Brotli. That typically reduces bandwidth and speeds up delivery of HTML, JSON, and JavaScript, which is why some frameworks enable it by default as a sensible production optimization. Others leave it off because compression is often handled more efficiently by a CDN or reverse proxy, and because it puts extra load on the CPU.</p>
<ul>
<li><p><strong>Next.js</strong>: Its built-in <code>compress</code> option works at the framework level, not just the HTTP server. We checked and confirmed that Next.js serves gzip responses with both Node and Watt, so compression is always applied no matter the runtime.</p>
</li>
<li><p><strong>TanStack Start</strong>: Never had compression configured in any runtime. All three runtimes (Node, PM2, Watt) served uncompressed responses. No inconsistency, but it made the comparison between frameworks unfair.</p>
</li>
<li><p><strong>React Router</strong>: does not ship a default server, but there are several templates. In the one we followed, compression was enabled; Watt did not follow the same example, and it had no compression.</p>
</li>
</ul>
<h3><strong>The Fix</strong></h3>
<p>We turned off compression on React Router by taking out the <code>compression()</code> middleware and uninstalling the package from <code>server.js</code>. We also set <code>compress: false</code> in Next.js’s <code>next.config.mjs</code> to make sure all three frameworks were tested the same way. Now, with compression removed everywhere, all frameworks serve uncompressed responses in every runtime.</p>
<p>In production, it’s best to handle compression at the reverse proxy or CDN layer, not in the application server.</p>
<hr />
<h2>Corrected Results</h2>
<p>All tests run at 1,000 req/s for 3 minutes with mixed e-commerce traffic (homepage, search, card details, game browsing, sellers - you can read more about the sample app we built for these benchmarks <a href="https://github.com/platformatic/k8s-watt-performance-demo/tree/ecommerce">here</a>) on AWS EKS. No compression, no <code>Accept-Encoding</code> headers.</p>
<p><strong>Software Versions</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/5bd6ba70-b6b3-43c2-a547-0487461d9cb0.png" alt="" style="display:block;margin:0 auto" />

<p><strong>React Router: Consistent Across All Runtimes</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/372ced00-f95d-43d8-9be2-770a6cb43e26.png" alt="" style="display:block;margin:0 auto" />

<p>React Router can handle 1,000 requests per second with no failures on any of the three runtimes. Watt and PM2 have almost the same median response time at 15ms. The difference shows up at the higher end: Watt’s p(99) is 83ms, PM2’s is 123ms, and Node’s is 298ms.</p>
<p><strong>TanStack Start: Watt and Node Neck-and-Neck</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/6150e74b-08b1-42da-ad43-c1678a29fe0f.png" alt="" style="display:block;margin:0 auto" />

<p>TanStack with Watt and TanStack with Node perform almost the same: they have the same average, median, and p(95) times. Watt is slightly better at p(99), with 89ms compared to Node’s 121ms.</p>
<p><strong>PM2 stands out as the outlier.</strong> With an 81% success rate and a 2.5 second average latency, PM2’s cluster fork model does not work well with Nitro’s srvx server. This is a problem between PM2 and Nitro, not TanStack. The same PM2 cluster mode works perfectly with React Router’s Express server, giving 100% success and a 20ms average.</p>
<p><strong>Next.js: Still Struggling at 1,000 req/s</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/ab2b2822-3331-485d-883f-11162aafcc10.png" alt="" style="display:block;margin:0 auto" />

<p>Next.js cannot handle 1,000 requests per second, no matter which runtime is used. All three runtimes have about a 55% success rate, which shows that <strong>the framework itself is the bottleneck, not the runtime</strong>. The high tail latencies (p(99) over 60 seconds) mean requests are piling up and timing out.</p>
<hr />
<h3><strong>What Changed vs the Original Blog Post</strong></h3>
<p><strong>Previous React Router Results (with compression inconsistency)</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/a3f37078-da72-4752-b6a9-b13be6a7a630.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Corrected React Router Results (no compression anywhere)</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/6c693170-5ef9-4c55-9d47-69d62e2fedcd.png" alt="" style="display:block;margin:0 auto" />

<p>The average latency numbers are similar because Node’s response time was mostly affected by SSR work, not compression. Still, making this correction is important for our methods. Now we can be sure the gap is real and not just a mistake.</p>
<p><strong>TanStack’s results were always fair. The numbers changed a bit (from 13ms to 18ms) because of normal differences between runs, not because of</strong> <strong>compression changes.</strong></p>
<hr />
<h3>Key Takeaways</h3>
<ol>
<li><p><strong>Benchmark Hygiene Matters</strong><br />A single middleware inconsistency, like having compression enabled in <code>server.js</code> but skipped by Watt, was enough to make our results questionable. Always make sure your test conditions are the same for every variant, especially when runtimes load applications in different ways.</p>
</li>
<li><p><strong>Watt’s Real Advantage: Tail Latency</strong><br />With compression turned off, Watt and Node have similar average and median latencies on both TanStack and React Router. However, Watt always comes out ahead at p(99):</p>
<img src="https://cdn.hashnode.com/uploads/covers/63f78b3e207712e9dab049ad/44ce9ddc-67de-4f5e-b1f4-05556c0733f7.png" alt="" style="display:block;margin:0 auto" />

<p>This is important for services where tail latency matters, like APIs for user-facing pages or services with strict SLAs.</p>
</li>
<li><p><strong>PM2 Cluster Mode Has Compatibility Issues</strong><br />PM2 works well with Express (React Router: 100% success, 20ms average), but not with Nitro (TanStack: 81% success, 2.5s average). If you use Nitro-based frameworks like TanStack Start or Nuxt, it’s better to <strong>avoid PM2 cluster mode</strong> and use Watt or plain Node instead.</p>
</li>
<li><p><strong>Next.js at 1,000 req/s: The Runtime Doesn’t Matter</strong><br />All three runtimes, Watt, PM2, and Node, perform the same on Next.js at this load, with about 55% success and a 9-second average. The bottleneck is in Next.js’s SSR pipeline, not in how connections are handled.<br />Part of the advantage of Watt is a better handling of CPU-bound activities, like compression. Disabling it reduces the advantage.</p>
</li>
<li><p><strong>TanStack Start and React Router Are Both Excellent</strong><br />With compression handled the same way, TanStack (18ms average) and React Router (19ms average on Watt) are very close in performance. Both can handle 1,000 requests per second with 100% success. So, you should choose between them based on developer experience and ecosystem fit, not just performance.</p>
</li>
</ol>
<hr />
<h2>Reproducing These Benchmarks</h2>
<p>The complete benchmark infrastructure is available at:<br /><a href="https://github.com/platformatic/k8s-watt-performance-demo/tree/ecommerce">https://github.com/platformatic/k8s-watt-performance-demo/tree/ecommerce</a></p>
<pre><code class="language-plaintext"># Benchmark TanStack Start
AWS_PROFILE=&lt;profile-name&gt; FRAMEWORK=tanstack ./benchmark.sh

# Benchmark React Router
AWS_PROFILE=&lt;profile-name&gt; FRAMEWORK=react-router ./benchmark.sh

# Benchmark Next.js
AWS_PROFILE=&lt;profile-name&gt; FRAMEWORK=next ./benchmark.sh
</code></pre>
<hr />
<h2>Conclusion</h2>
<p>Getting benchmarks right is tough. Even if you have the same applications, the same infrastructure, and careful methods, one small inconsistency, like compression middleware in one framework’s server file that is skipped by one runtime but not others, can make your results questionable.</p>
<p>The corrected results support the main points from our original post: TanStack Start and React Router can easily handle 1,000 requests per second, Next.js struggles at that level, and Watt gives real improvements across all three frameworks, especially for tail latencies. Now, though, we have more accurate numbers and a better idea of where each runtime really helps.</p>
<p>Being open about our methods is important. We made a mistake, fixed it, and are sharing both the error and the fix so others can learn from our experience.</p>
<p>If you’d like to talk about using Watt in your setup or want to learn more, email us at <a href="mailto:hello@platformatic.dev">hello@platformatic.dev</a> or reach out to<a href="https://www.linkedin.com/in/lucamaraschi/">Luca</a> or<a href="https://www.linkedin.com/in/matteocollina/">Matteo</a> on LinkedIn.</p>
]]></content:encoded></item></channel></rss>