Skip to content

Fail over to on-premise#

At an airport with an on-premise node, clients inside the airport network should keep working when the internet link fails. This guide gives the rules for when to switch between the edge and the node, and a client that follows them.

On-premise nodes are part of Preview 2. Read Edge and on-premise first for how the two nodes share state. Clients outside the airport network cannot reach the node and need none of this.

What each node serves#

Edge On-premise node
Reads, searches, observations Full history Last 72 hours; older reads forwarded to the edge
Event streams and replay Yes Yes, within 72 hours
Pushing records Yes Yes
Feeds, mappings, applications, keys, webhooks Yes Forwarded to the edge; 503 not_primary while it is unreachable
Scenarios Yes No

The rules#

Default
Send every request to the edge, https://api.surfacelens.app/v1.
Switch to the node
When a request to the edge fails to connect, or times out after 5 seconds, or returns 502, 503 or 504 without a Retry-After header, three times within 10 seconds.
While on the node
Probe the edge with GET /v1/status every 15 seconds.
Switch back
After three probes in a row succeed. The node keeps working after the edge recovers, forwarding to it, so there is no hurry.
Never switch on
4xx errors, or 503 with Retry-After. Those are answers, not outages.

The thresholds avoid switching on a single slow response and avoid flapping on an unstable link. The node itself promotes to primary 30 seconds after losing the edge, so a client that switched earlier is served reads at once and has its writes admitted from that point.

A client that follows them#

The airport object tells you the node's base URL. Read it once at start-up and keep it in configuration.

const EDGE = "https://api.surfacelens.app/v1";
const NODE = "https://surfacelens.vtbs.internal/v1";
const headers = { Authorization: `Bearer ${process.env.SURFACELENS_KEY}` };

let active = EDGE;
let failures: number[] = [];

function isOutage(res: Response) {
  return [502, 503, 504].includes(res.status) && !res.headers.has("Retry-After");
}

export async function call(path: string, init: RequestInit = {}): Promise<Response> {
  const base = active;
  try {
    const res = await fetch(base + path, {
      ...init,
      headers: { ...headers, ...init.headers },
      signal: AbortSignal.timeout(5000),
    });
    if (base !== EDGE || !isOutage(res)) return res;
  } catch (error) {
    if (base !== EDGE) throw error;
  }
  const now = Date.now();
  failures = [...failures.filter((t) => now - t < 10_000), now];
  if (failures.length >= 3) {
    active = NODE;
    probeEdge();
  }
  return fetch(active + path, { ...init, headers: { ...headers, ...init.headers } });
}

async function probeEdge() {
  let ok = 0;
  while (active === NODE) {
    await new Promise((r) => setTimeout(r, 15_000));
    const res = await fetch(`${EDGE}/status`, { headers, signal: AbortSignal.timeout(5000) })
      .catch(() => null);
    ok = res?.ok ? ok + 1 : 0;
    if (ok >= 3) {
      active = EDGE;
      failures = [];
    }
  }
}
import os, threading, time, httpx

EDGE = "https://api.surfacelens.app/v1"
NODE = "https://surfacelens.vtbs.internal/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SURFACELENS_KEY']}"}

class Gateway:
    def __init__(self):
        self.active = EDGE
        self.failures: list[float] = []
        self.client = httpx.Client(headers=HEADERS, timeout=5)

    def _outage(self, res: httpx.Response) -> bool:
        return res.status_code in (502, 503, 504) and "Retry-After" not in res.headers

    def request(self, method: str, path: str, **kwargs) -> httpx.Response:
        base = self.active
        try:
            res = self.client.request(method, base + path, **kwargs)
            if base != EDGE or not self._outage(res):
                return res
        except httpx.TransportError:
            if base != EDGE:
                raise
        now = time.monotonic()
        self.failures = [t for t in self.failures if now - t < 10] + [now]
        if len(self.failures) >= 3:
            self.active = NODE
            threading.Thread(target=self._probe_edge, daemon=True).start()
        return self.client.request(method, self.active + path, **kwargs)

    def _probe_edge(self):
        ok = 0
        while self.active == NODE:
            time.sleep(15)
            try:
                ok = ok + 1 if self.client.get(f"{EDGE}/status").is_success else 0
            except httpx.TransportError:
                ok = 0
            if ok >= 3:
                self.active, self.failures = EDGE, []

Writes#

Records are deduplicated by record_id on both nodes and across the merge. If a push to the edge times out, send the same batch to the node. Records the edge had already admitted come back as duplicate once the two nodes reconcile; nothing is admitted twice.

Other writes carry an Idempotency-Key. Keys are honoured by the node that received them, and replicated with the merge, so a retry with the same key on either side after recovery returns the original result.

Streams#

Keep the last event ID, as in Subscribe to changes. On failover, reconnect to the other base URL with the same Last-Event-ID. Both nodes understand epoch:revision IDs. If the merge changed entities you already hold, the stream sends their new state as entity.snapshot events before it continues.

Know where you are#

Every response carries SurfaceLens-Node: edge; colo=BKK or onprem; id=vtbs-gw-1. Log it with your request IDs. A dashboard that shows which node served the last request makes an outage obvious to the people on shift.

Test it#

Test keys accept a SurfaceLens-Simulate: edge_unavailable header, which makes the edge answer 503 without Retry-After, as it would in an outage. Each test application also has a sandbox node at https://sandbox-node.surfacelens.app/v1. Point NODE at it and run your client with the header set.