How Camofox-Browser Fly.io Replay Middleware Routes Tab Requests to Owning Machines

Camofox-Browser uses machine-prefixed tab IDs and a custom Express middleware to detect non-local requests and trigger Fly.io's replay mechanism, routing HTTP requests to the specific machine that owns each browser tab.

The camofox-browser Fly.io replay middleware enables horizontal scaling across a Fly.io cluster by ensuring that browser tab requests are always processed by the machine that created the tab. When running in a distributed environment, the system embeds machine identifiers directly into tab IDs and uses HTTP response headers to instruct Fly's edge router to replay requests on the correct instance. This architecture lives in lib/fly.js and integrates seamlessly with the Express application defined in server.js.

Tab ID Structure and Ownership

The routing strategy depends on encoding ownership information directly into the tab identifier. Each tab ID combines the Fly machine ID with a UUID, creating a deterministic way to locate the owning server instance.

Generating Machine-Prefixed IDs

The makeTabId function in lib/fly.js (lines 16-19) constructs tab IDs by prefixing a standard UUID with the current machine's ID:

function makeTabId() {
  const uuid = crypto.randomUUID();
  return machineId ? `${machineId}_${uuid}` : uuid;
}

When the FLY_MACHINE_ID environment variable is present, the function returns a composite ID in the format {machineId}_{uuid} where machineId is a 14-character hexadecimal string. If the service is not running on Fly, the helper returns a plain UUID and all replay logic becomes a no-op.

Parsing the Owner Machine

The parseTabOwner function (lines 21-30) extracts the machine identifier from a given tab ID:

function parseTabOwner(tabId) {
  if (!machineId || !tabId) return null;
  const idx = tabId.indexOf('_');
  if (idx === -1) return null;               // legacy without machine prefix
  const candidate = tabId.slice(0, idx);
  if (candidate.includes('-')) return null;  // UUID segment, not a machine ID
  return candidate;                           // the machineId part
}

This helper validates the tab ID structure and returns the machine identifier portion, ensuring backward compatibility with legacy tab IDs that lack the machine prefix.

Fly.io Replay Middleware Implementation

The core routing logic resides in the Express middleware that intercepts tab-specific requests and decides whether to process them locally or trigger a replay to another machine.

Local vs Remote Detection

Before determining routing, the system checks if the current machine owns the requested tab using the isLocalTab function (lines 32-35):

function isLocalTab(tabId) {
  const owner = parseTabOwner(tabId);
  return owner === null || owner === machineId;
}

The function returns true when the tab owner matches the current machineId or when no ownership information is present, allowing the request to proceed through the local middleware stack.

The Replay Logic

The replayMiddleware function (lines 41-50) handles the actual routing decision:

function replayMiddleware(log) {
  return (req, res, next) => {
    if (!machineId) return next();                 // no Fly, skip
    const tabId = req.params.tabId;
    if (!tabId || isLocalTab(tabId)) return next(); // owned locally
    const owner = parseTabOwner(tabId);
    log('info', 'fly-replay', { reqId: req.reqId, tabId, owner, self: machineId });
    res.set('fly-replay', `instance=${owner}`);
    res.status(307).send();                         // ask Fly's router to forward
  };
}

When a request targets a tab owned by a different machine, the middleware:

  1. Logs the replay attempt with request metadata
  2. Sets the HTTP header fly-replay: instance={owner}
  3. Returns a 307 Temporary Redirect status with an empty body

Fly's internal load balancer intercepts this response and forwards the request to the instance matching the specified machine ID, ensuring the owning server processes the tab's actions.

Server Integration

The middleware is wired into the Express application in server.js (lines 87-93):

const fly = createFlyHelpers(CONFIG);
app.use('/tabs/:tabId', fly.replayMiddleware(log));

This mounting pattern applies the replay logic to all routes containing the :tabId parameter, including /tabs/:tabId/navigate and /tabs/:tabId/snapshot. According to the camofox-browser source code, this integration ensures that any request path with a tab identifier automatically passes through the replay validation layer.

Graceful Degradation Without Fly.io

When running outside the Fly.io environment, the system disables routing overhead automatically. If CONFIG.flyMachineId is empty (the default when FLY_MACHINE_ID is not set), the machineId variable becomes an empty string, causing:

  • makeTabId to generate plain UUIDs without machine prefixes
  • isLocalTab to always return true
  • replayMiddleware to immediately invoke next() and skip replay logic

This design allows the same codebase to function identically in local development and production Fly.io deployments without configuration changes.

Practical Code Examples

Creating a new tab with the Fly-aware helper:

const fly = createFlyHelpers(CONFIG);
const tabId = fly.makeTabId();   // e.g., "abcd1234ef56_9f8b7c6d-..."

Handling client requests that cross machine boundaries:

// Client requests: GET /tabs/abcd1234ef56_9f8b7c6d-.../snapshot
// Express matches '/tabs/:tabId' and executes replayMiddleware

// If machineId is "xyz987" but tab owner is "abcd1234ef56":
// Response headers:
// fly-replay: instance=abcd1234ef56
// Status: 307 Temporary Redirect

Conditional local processing:

if (fly.isLocalTab(tabId)) {
  // Process request directly - no replay header emitted
  await handleTabAction(tabId);
}

Summary

  • Camofox-browser embeds Fly machine IDs directly into tab identifiers using the format {machineId}_{uuid} via the makeTabId function in lib/fly.js.
  • The replay middleware inspects incoming requests at /tabs/:tabId, extracts the owner machine from the tab ID, and emits a fly-replay header when the request arrives on the wrong instance.
  • Fly's edge router intercepts the 307 response containing the fly-replay: instance={owner} header and transparently forwards the request to the owning machine.
  • When not running on Fly.io, the middleware chain bypasses replay logic entirely, returning plain UUIDs and processing all requests locally.
  • This architecture enables horizontal scaling across multiple identical server instances while maintaining tab affinity without application-layer session management.

Frequently Asked Questions

How does camofox-browser maintain tab affinity across multiple Fly.io machines?

Camofox-browser maintains tab affinity by embedding the originating machine's ID into each tab identifier using the makeTabId function. When a request arrives for a specific tab, the replayMiddleware in lib/fly.js parses the tab ID to determine the owning machine. If the request landed on a different instance, the middleware returns a 307 status with a fly-replay header instructing Fly's router to forward the request to the correct machine.

What happens if a request contains a legacy tab ID without a machine prefix?

The parseTabOwner function handles legacy tab IDs by checking for the underscore separator and validating the prefix format. If no underscore is found or if the prefix contains hyphens (indicating a UUID segment), the function returns null. This causes isLocalTab to return true, allowing the current machine to process the request rather than attempting to route it.

Can the replay middleware be disabled for local development?

The replay middleware automatically disables itself when the FLY_MACHINE_ID environment variable is not present. In this case, createFlyHelpers sets machineId to an empty string, causing replayMiddleware to immediately call next() without setting replay headers. This allows the application to run locally without Fly-specific routing overhead while using identical code paths.

What HTTP status code does the replay middleware return?

The replay middleware returns HTTP 307 Temporary Redirect when routing a request to a different machine. This status code, combined with the fly-replay: instance={owner} response header, signals to Fly's internal infrastructure that the request should be transparently replayed on the specified target instance rather than processed by the current machine.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →