Skip to content

mkdir Is a Lock

Published:

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:

  1. opens the list,
  2. adds a line,
  3. saves it.

Now start two apps at the same moment:

  1. App A opens the list. It is empty.
  2. App B opens the list. It is still empty.
  3. A adds web and saves.
  4. B adds api and 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:

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:

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.

Check Open Ports on Your VPS with nmap
Portless: Need of the Hour