While reading the Portless source, I found a folder called routes.lock sitting next to routes.json in ~/.portless. It turns out to be a lock, and the trick behind it is simpler than I expected.
The problem
Portless keeps one list of every running app and its port in routes.json. Each time you start an app, Portless:
- opens the list,
- adds a line,
- saves it.
Now start two apps at the same moment:
- App A opens the list. It is empty.
- App B opens the list. It is still empty.
- A adds
weband saves. - B adds
apiand saves, wiping out A’s change.
The list now only has api. web is running, but its URL is dead, and nothing reports an error. This is called a lost update, and it is very likely when several AI agents spin up dev servers in parallel.
The fix: a bathroom door lock
Before touching the list, a process locks the door. Anyone else who arrives waits outside and tries again in a moment. When the first one is done, it unlocks the door and the next one goes in. Changes happen one at a time, so none get lost.
The “lock” is a directory. Creating a directory with mkdir is atomic on every OS: if two processes call it at the same instant, exactly one succeeds and the other gets EEXIST. So:
- Got the lock means
mkdirsucceeded. - Someone else has it means
mkdirfailed withEEXIST. - Release means remove the directory.
No native modules or OS-specific locking APIs are needed. It works the same on macOS, Linux and Windows.
Simulate it in Node.js
This script starts 5 child processes at the same moment. Each one reads the list, does a bit of “work”, appends its name and writes the list back.
// race.mjs -> node race.mjs (no lock)
// node race.mjs --lock (mkdir lock)
import { fork } from "node:child_process";
import fs from "node:fs";
const FILE = "routes.json";
const LOCK = "routes.lock";
const useLock = process.argv.includes("--lock");
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function acquireLock() {
while (true) {
try {
fs.mkdirSync(LOCK); // atomic: only one process can create it
return;
} catch (err) {
if (err.code !== "EEXIST") throw err;
await sleep(5 + Math.random() * 10); // someone else has it, retry
}
}
}
const releaseLock = () => fs.rmSync(LOCK, { recursive: true, force: true });
async function addRoute(name) {
if (useLock) await acquireLock();
try {
const routes = JSON.parse(fs.readFileSync(FILE, "utf8")); // 1. read
await sleep(Math.random() * 20); // 2. do some work
routes.push(name); // 3. change
fs.writeFileSync(FILE, JSON.stringify(routes)); // 4. write back
} finally {
if (useLock) releaseLock();
}
}
if (process.env.APP_NAME) {
// child: one "portless run" registering its app
await sleep(Math.max(0, Number(process.env.START_AT) - Date.now())); // all start together
await addRoute(process.env.APP_NAME);
} else {
// parent: start 5 apps at the same moment
fs.writeFileSync(FILE, "[]");
releaseLock();
const apps = ["web", "api", "docs", "admin", "blog"];
const START_AT = String(Date.now() + 500);
await Promise.all(
apps.map(
name =>
new Promise(done =>
fork(process.argv[1], process.argv.slice(2), {
env: { ...process.env, APP_NAME: name, START_AT },
}).on("exit", done)
)
)
);
const saved = JSON.parse(fs.readFileSync(FILE, "utf8"));
console.log(useLock ? "with lock: " : "without lock:", saved);
console.log(`${saved.length} of ${apps.length} routes saved`);
}
Output on my machine:
$ node race.mjs
without lock: [ 'web', 'docs' ]
2 of 5 routes saved
$ node race.mjs --lock
with lock: [ 'docs', 'web', 'api', 'blog', 'admin' ]
5 of 5 routes saved
Without the lock, three of five apps silently disappear. With it, all five are saved every time.
What Portless adds on top
The demo is the core idea. The real version handles the cases that bite in practice:
- Someone leaves without unlocking. If a process crashes while holding the lock, the folder stays forever. Portless writes its PID into
routes.lock/owner. If the lock is older than 10 seconds and that PID is no longer running, it removes the lock and moves on. A slow but alive process keeps its lock. - Nobody waits forever. Retries back off from 10ms up to 100ms with random jitter, so waiting processes don’t keep colliding. After 15 seconds it gives up with an error instead of hanging.
- Readers don’t need the lock. The proxy only reads the list. Writers save to
routes.json.tmpand thenrenameit overroutes.json. Rename is atomic too, so a reader always sees the whole old file or the whole new one, never a half-written one.
Takeaway
When several processes share one file, “read, change, write” needs a lock. mkdir gives you one in a single line, and atomic rename keeps readers safe without making them wait.