I build a system that runs agents on remote machines. Those machines sit behind NAT or an organization’s firewall, and nobody can open an inbound port on them. Even if the controlling side (the server, below) wrote down a machine’s address, nothing sent to it would arrive.

So the server never connects to a machine. There are only three paths:

  1. During installation only, a person connects with the SSH access they already have.
  2. After that, the machine reports liveness over outbound HTTPS and fetches work with a separate request.
  3. File contents and process I/O travel over that person’s SSH, and only while they are there.

This post is mostly about the second path: how to treat silence, and how to pin the destination of work.

Every arrow starts at the machine

A NAT mapping only keeps flows that were opened from the inside, and only for a while. An outbound connection gets through every time, and when a mapping expires, the next check-in restores the relationship. The server does not store machine addresses.

The check-in carries no file contents and no process I/O. If a large transfer stalls, the machine would look offline for that reason alone. Fetching work is a separate short request too.

At installation, the credential goes over SSH’s standard input. On the command line it would show up in the process list. In a service definition, or in the environment the service manager passes to the process, anyone who can read the definition can read the credential. The machine writes it to a temporary file that is already owner-only, then renames it into place.

Telling “stopped” from “gone”

The server returns the check-in interval in every response. If the client had it built in, changing the interval would mean shipping a new binary. The floor is a few tens of seconds. The machine also checks in right away, without waiting for the interval, when it receives a credential, when its readiness changes, and just before it stops.

That last check-in, sent just before stopping, is what lets the server tell “stopped” from “gone”. A machine whose last word was “running” and then went quiet is not stopped, it is unknown. A crash, sleep and a dead network all look like the same silence from the server.

The server decides from two things only: the time of the last check-in and the last thing the machine said. There is no path for asking the machine.

package presence

import "time"

// Fresh is how recent the last check-in must be to count as online.
const Fresh = 2 * time.Minute

// State is computed from the last check-in only. The machine is never asked.
// Silence means "stopped" only if the last thing it said was "stopping".
func State(last time.Time, lastSaid string, now time.Time) string {
	switch {
	case last.IsZero():
		return "never-seen"
	case lastSaid == "stopping":
		return "stopped"
	case now.Sub(last) < Fresh:
		return "online"
	default:
		return "unknown" // a crash, sleep and a dead network all look like this
	}
}

A check-in counts as fresh for about two minutes.

Sometimes the server needs something from the machine, such as the tail of its log. It cannot dial, so the request rides on the check-in response. The server writes the time of the request on the machine’s row. The machine sees it in the next response and uploads with a separate outbound request. The upload stays out of the check-in for the same reason as above. A request made while the machine is down is not a failure. It arrives when check-ins resume.

Silence does not move work to another machine

Work has more than one entry point: starting it from the local UI and putting it on a queue. If the destination were chosen when a machine comes to fetch work, whichever live machine asks first would win, and the machine a person picked could differ from the one that ran the work. A silent machine is not necessarily dead either. If the work moves and the machine comes back, both copies are left behind.

So there are three rules:

  • The destination (machine and placement generation) is written when the work is submitted. A machine can only fetch work addressed to it.
  • Each work surface, meaning work that uses the same place on disk, has at most one open admission to start.
  • A request retried after a lost response gets the same admission back. The same identifier with different contents is a conflict and is refused.

Unstarted work older than half a day is not handed to another machine either. It is recorded as expired the next time its own machine comes to fetch. Deleting a machine’s row does not delete its open admissions. If it did, a late copy of the same request could get a second admission.

The smallest PostgreSQL version looks like this:

CREATE TABLE surfaces (
  id         bigint PRIMARY KEY,
  machine_id text   NOT NULL,
  generation int    NOT NULL DEFAULT 1
);

CREATE TABLE admissions (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  surface_id bigint NOT NULL REFERENCES surfaces (id),
  machine_id text   NOT NULL,  -- fixed when the work is submitted
  generation int    NOT NULL,
  request_id text   NOT NULL,
  attempt    int    NOT NULL,
  digest     text   NOT NULL,
  closed_at  timestamptz,
  UNIQUE (request_id, attempt)
);

-- At most one open admission per surface. Closed rows stay as history.
CREATE UNIQUE INDEX one_open_admission ON admissions (surface_id)
  WHERE closed_at IS NULL;

Asking for an admission is one statement:

-- $1 surface, $2 request id, $3 attempt, $4 digest, $5 generation the caller saw
INSERT INTO admissions (surface_id, machine_id, generation, request_id, attempt, digest)
SELECT id, machine_id, generation, $2, $3, $4
FROM surfaces
WHERE id = $1 AND generation = $5
ON CONFLICT (request_id, attempt) DO NOTHING
RETURNING id;

I ran the four cases on PostgreSQL 17:

CaseResultWhat the caller does
First requestAn id comes backAdmitted
Retry with the same request_id and attemptNothing comes backLook up (request_id, attempt). Same digest: return the earlier admission. Different: conflict
Another request for a surface with an open admissionUnique violation on one_open_admissionSomeone already owns it
The generation the caller saw is staleNothing comes back, and the lookup finds no rowPlacement changed, refuse

ON CONFLICT only swallows conflicts on the (request_id, attempt) it names. A violation of the partial unique index comes back as an error, so a retry is never mistaken for another owner.

Lock the parent with FOR NO KEY UPDATE, not FOR UPDATE

Work that reads a surface row, decides, and rewrites it (a placement change, say) locks the row to serialize. With SELECT ... FOR UPDATE, it waits for every in-flight transaction that is inserting an admission for that surface.

Inserting a child row makes the foreign key check take FOR KEY SHARE on the parent and hold it until the transaction ends. In the row lock conflict table, the only mode that conflicts with FOR KEY SHARE is FOR UPDATE. An UPDATE that does not change key columns takes only FOR NO KEY UPDATE itself, so taking FOR UPDATE first locks harder than the write that follows.

Two sessions show it. The first inserts an admission and keeps its transaction open.

-- session 1
BEGIN;
INSERT INTO admissions (surface_id, machine_id, generation, request_id, attempt, digest)
VALUES (1, 'm1', 1, 'r9', 1, 'd9');  -- the FK check holds FOR KEY SHARE on surfaces(1)
SELECT pg_sleep(4);
ROLLBACK;
-- session 2, started while session 1 is open
SET lock_timeout = '1s';
BEGIN;
SELECT generation FROM surfaces WHERE id = 1 FOR NO KEY UPDATE;
ROLLBACK;
BEGIN;
SELECT generation FROM surfaces WHERE id = 1 FOR UPDATE;
ROLLBACK;
 generation
------------
          1
(1 row)

ERROR:  canceling statement due to lock timeout
CONTEXT:  while locking tuple (0,1) in relation "surfaces"

FOR NO KEY UPDATE returned at once, and FOR UPDATE timed out after one second. With lock_timeout, “did it wait?” becomes a fixed error instead of a timing measurement. FOR NO KEY UPDATE conflicts with itself, so two transitions on the same surface are still serialized. I checked that with the same method, and it timed out too.

Sometimes the lock should stay strong. If the transaction deletes the row or changes its key, it needs FOR UPDATE anyway, so take that from the start. Upgrading from a weaker lock is a classic way to get a deadlock. If blocking child inserts is the point, say so with a check on the child’s write path instead of relying on a side effect of the lock mode.

When not to use this

  • You manage the machine’s network and can reach it. Inside one LAN or your own VPN, connecting from the server directly is simpler.
  • The work does not depend on state on the machine. If no files or in-progress work stay on the machine, moving a silent machine’s work elsewhere is fine. The destination is pinned to keep that context from splitting.
  • There is only one machine. There is no destination to choose, so the admission machinery is unnecessary.

Unreachable is not the same as gone

With a peer you cannot dial, the relationship lives only on short connections the peer makes. Silence stays “unknown” and is never called a stop. The destination of work is decided at submission and does not move because of silence. That keeps “unreachable” from being mixed up with “gone”.