openship icon indicating copy to clipboard operation
openship copied to clipboard

[Improvement]: Skip unchanged edge writes and batch route registration on deploy

Open rudik99 opened this issue 1 month ago • 2 comments

Existing issue

  • [x] I have searched the existing issues and found no duplicate.

Current behavior

On every deploy, registerProjectRoutes (packages/adapters/src/runtime/route-registration.ts) handles each hostname of a service one at a time. For each hostname it:

  1. calls registerRoute, which writes the vhost and route-state sidecar through updateConfig and reloads the edge;
  2. calls provisionCert. When a valid certificate already exists, it calls activateCert → activateRouteCert → registerRoute again, which writes the same files and reloads a second time.

On a redeploy where nothing about routing changed (same host port, same certificates), every one of those writes produces exactly the content already on disk. A service with N hostnames therefore does 2N full write-and-reload cycles for no change.

On a remote server this is dominated by SSH round trips. Our setup:

  • self-hosted control plane, v0.9.5;
  • app server with a containerised edge, reached over SSH at about 340 ms round-trip time;
  • one storefront service with 9 custom hostnames.

Every remote operation, even true, costs about 1.4 s there. Per-hostname timings from deploy logs:

Step v0.9.3 (18 Oct) v0.9.5 (25 Oct onward)
Write route + reload (Registering route → Checking SSL) 21 s 47 s
Read certificate (Checking SSL → Requesting SSL certificate) 3 s 6 s
Re-activate existing certificate (→ SSL certificate active) 29 s 60 s
Per hostname ~53 s ~113 s
9 hostnames ~8 min ~17 min

The doubling between v0.9.3 and v0.9.5 coincides with the extra reads now done on each route write: the route-state sidecar and existing vhost checks for password protection, resolveCertificate, and file snapshots. Each is reasonable alone, but they are paid twice per hostname, one hostname at a time.

Two side effects:

  • The deployment record's updatedAt doesn't move during this phase, so a 17-minute route phase looks like a hung deploy. We cancelled one believing it was stuck.
  • The rest of the services (for example, CMS, ecomm app, databases) only roll out after every hostname is done.

Proposed improvement

One PR with two commits, so the first can merge on its own if preferred.

1. Skip unchanged writes in updateConfig (packages/adapters/src/infra/nginx.ts)

updateConfig already captures a snapshot of every target file before writing. Drop any change whose content equals the snapshot (or that removes a file that doesn't exist). If nothing remains, return without writing and without reloading:

const pending = changes.filter(({ content }, i) => {
  const { snapshot } = snapshots[i]!;
  return content === null ? snapshot.exists : !snapshot.exists || snapshot.content !== content;
});
if (!pending.length) return;

The rollback path keeps using the full snapshots list. This makes the redundant activateCert re-registration, and the whole route write on an unchanged redeploy, free apart from the reads.

To be conservative, the skip could apply only when no earlier reload failed in this provider instance, so a previous write that never reached the running config is still reloaded.

2. Batch route registration

Add registerRoutes(routes: RouteConfig[]) to the routing provider and use it from registerProjectRoutes. Under a single withConfigLock:

  • resolve certificates for all hostnames, issuing the reads concurrently over the shared SFTP channel;
  • render every vhost (HTTPS directly where a valid certificate already exists);
  • make one updateConfig call with all files and do one reload.

Then run certificate issuance only for hostnames that are missing a certificate or near expiry. That stays serial under the existing per-server ACME lock, followed by a single activation reload.

Per-hostname error reporting and the existing retry and "edge down" handling stay the same: a failure in the batch falls back to the current per-hostname path, so one bad hostname still can't fail the deploy.

Simply running the current loop in parallel wouldn't help: registerRoute, activateCert and resolveCertificate all take the same per-edge config lock, so the work would just queue.

Benefits

  • Anyone running a remote server, especially with several hostnames or high latency to the control plane, gets much faster deploys. Estimates for 9 hostnames at about 340 ms round-trip time:
    • commit 1 only: the route phase drops from about 17 minutes to a few minutes on unchanged redeploys;
    • both commits: about 1–2 minutes, with 1 reload instead of 18 (zero when nothing changed).
  • Fewer edge reloads on every deploy, which is less churn for live traffic.
  • Less SSH traffic, and less work under the edge config lock that other projects on the same server wait on.

Additional context

  • Version: control plane and edge v0.9.5, self-hosted; app server is Ubuntu on ARM with a containerised edge and a non-root SSH user.
  • Measured cost of a no-op remote exec (true, docker exec <edge> true) from the control plane: about 1.4 s each.
  • Happy to submit the PR (both commits with tests) if this approach works for you. Tests would cover:
    • registering the same route twice performs zero writes and zero reloads the second time;
    • a changed upstream port still writes and reloads;
    • a batch of N routes performs one reload.

rudik99 avatar Nov 01 '26 06:11 rudik99

Follow-up after testing the first commit locally on our v0.9.5 instance. As proposed above, it barely helped (about 113 s → 96 s per hostname). Two details explain why, and both matter for the PR.

1. The container read path strips the trailing newline, so the content comparison never matches

When a host read misses, readMaybeInContainer (packages/adapters/src/system/edge-container-executor.ts:82) falls back to docker exec … cat <path>. The SSH executor resolves command output with stdout.trim() (packages/adapters/src/system/ssh-executor.ts:610). The snapshot therefore loses the vhost's trailing newline, and snapshot.content !== content is always true even when nothing changed.

Comparing with trimEnd() on both sides fixed it for us:

return (
  !snapshot.exists ||
  snapshot.linkTarget !== undefined ||
  (snapshot.content ?? "").trimEnd() !== content.trimEnd()
);

A cleaner upstream fix may be to stop trimming file content read through exec (or read it with a sentinel), so snapshots are byte-exact.

2. Why the reads hit the container path at all

On our app server the vhost files under the edge sites directory are root:root 0600, while Openship connects as a non-root SSH user. Every host readFile fails, so each read pays for a failed host read, docker ps to resolve the edge container, and docker exec cat: three remote round trips per file instead of one. That is most of the remaining cost per hostname.

Measured on our instance (9-hostname storefront, about 340 ms RTT, staging refresh deploys):

Version Per hostname
v0.9.5 unpatched ~113 s
Commit 1 as originally proposed ~96 s
Commit 1 with the trimEnd comparison ~56 s

With the patched comparison, re-registering an unchanged route does zero writes and zero reloads, and a changed upstream port still writes and reloads.

Suggestions for the PR, beyond the original two commits:

  • Make snapshot reads byte-exact (or compare ignoring trailing whitespace) so the skip works with containerised edges.
  • Write vhost files with permissions the SSH user can read (for example group-readable by the SSH user), or cache the resolved edge container per operation so the fallback does not repeat docker ps for every file.

We're running this as a temporary local patch until there is an upstream fix.

rudik99 avatar Nov 01 '26 10:11 rudik99

Update after re-checking this against current main (ef893be5d). The problem is still there, but two parts of my report were wrong, so I've changed the plan before opening a PR.

1. Which read trims the content. It isn't readMaybeInContainer. The container edge provider uses edgeContainerExecutor(..., { files: "host" }), so vhost reads go through elevatedExecutor. When the non-root login can't read a root 0600 file, readFileElevated falls back to sudo cat, and SshExecutor.exec trims that output. Each such read costs two round trips (the refused SFTP read, then sudo cat), not three. There's no docker ps per file. Because of the same trim, writeEdgeChallenge's existing "already on disk" check never matches on these hosts, and a rollback that restores a trimmed snapshot writes the file back without its trailing newline.

2. The skip I proposed isn't safe as written:

  • Certificates. Issuance and uploads put new material at the paths the vhost already names, so the vhost text doesn't change but the edge still has to reload. activateCert has to keep reloading.
  • Running config. Matching bytes on disk don't prove the edge is running them. A process could have died between the write and the reload. Until a provider has seen a reload succeed, it should reload once even when it writes nothing.
  • Comparison. It has to be exact, and it has to check the file mode as well as the content. Otherwise a mode change such as #1605's would never reach files whose content already matches. trimEnd() hides the trim bug; it doesn't fix it.

3. I'm withdrawing the batching commit. The replayRoutes comment explains why each route gets its own openresty -t, and once unchanged writes are skipped, batching saves little.

Revised plan: one PR with three commits. Each commit is self-contained and can be reviewed on its own; each builds on the one before.

  • 1. Stop trimming file reads that go through exec: the sudo fallback, the container fallback, and DockerEdgeExecutor in container file mode. exec itself is unchanged.
  • 2. Skip unchanged writes in updateConfig:
    • Compare content and mode. The mode comes from a new optional CommandExecutor.lstat.
    • When nothing changes, skip the reload only once this provider has seen the edge load what's on disk.
    • activateCert always reloads.
    • Remote servers get a new provider per deployment, so an unchanged deploy of HTTP-01 hostnames costs one confirming reload instead of two per hostname. DNS-01 and wildcard hostnames, which the platform activates directly, still reload once each, so an unchanged DNS-01 deploy costs one confirming reload plus one per hostname.
  • 3. Fewer repeated remote operations:
    • A per-lock-turn cache of route files.
    • exists trusts SFTP's "no such file" instead of running sudo test -e.
    • The sites directory is created once per provider.

Remote operations for an unchanged redeploy of nine HTTP-01 TLS hostnames through a non-root login. These are provider-level counts (registerRoute + provisionCert per host) from a fake executor that refuses unelevated reads of the sites and certificate directories; they exclude the platform's per-host certificate pre-check:

remote execs (of which sudo) SFTP ops reloads
main 459 (351) 414 18
commit 1 387 (315) 396 18
commits 1–2 226 (226) 326 1
commits 1–3 56 (56) 317 1

At our server's latency (about 1.4 s per remote exec, sudo or not, and about 0.34 s per SFTP request), that's an estimated 87 s of round trips per hostname on main, down to about 20 s, before counting the reloads themselves (18 → 1).

This doesn't change file permissions. Every file is still written 0600, and the mode comparison takes each file's desired mode, so it should combine cleanly with #1605.

rudik99 avatar Nov 08 '26 00:11 rudik99