# Archify Orthogonal Connection Routing Algorithm: Implementation Details and Usage

> Explore Archify's orthogonal connection routing algorithm. Learn how it generates clean L-shaped polylines by computing midpoints and validating routes against component boundaries. Implement and use Archify today.

- Repository: [tt-a1i/archify](https://github.com/tt-a1i/archify)
- Tags: internals
- Published: 2026-08-31

---

**Archify's orthogonal connection routing algorithm generates clean L-shaped polylines by computing axis-aligned midpoints and validating routes against component boundaries.**

The `archify/renderers/architecture/render-architecture.mjs` module contains the core implementation of how diagram connections are transformed into readable, orthogonal paths. When you specify `orthogonal-h` or `orthogonal-v` as a route type, the engine produces predictable horizontal-first or vertical-first dogleg connections that avoid visual clutter in architecture diagrams.

## How Orthogonal Routing Works in Archify

### The routeVia Function: Entry Point for Path Generation

The `routeVia` function (lines 14–30) is the central dispatcher that determines which intermediate points to insert between two anchors. According to the Archify source code, this function handles three explicit routing modes and delegates to automatic heuristics when no route is specified:

```js
function routeVia(conn, from, to, start, end, fromSide, toSide) {
  if (conn.via) return conn.via;
  switch (conn.route || 'auto') {
    case 'straight':
      return [];                                   // straight line
    case 'orthogonal-h': {                        // horizontal‑first dogleg
      const midX = (start[0] + end[0]) / 2;
      return [[midX, start[1]], [midX, end[1]]];
    }
    case 'orthogonal-v': {                        // vertical‑first dogleg
      const midY = (start[1] + end[1]) / 2;
      return [[start[0], midY], [end[0], midY]];
    }
    // …auto routing omitted for brevity…
  }
}

```

**Key characteristics of this implementation:**

- **`orthogonal-h`** computes `midX = (start[0] + end[0]) / 2` and returns two points that force horizontal travel first, then vertical
- **`orthogonal-v`** computes `midY = (start[1] + end[1]) / 2` and returns two points that force vertical travel first, then horizontal
- Both modes produce exactly two intermediate points, creating a crisp L-shape
- The final SVG path is constructed as `start → [mid, start[1]] → [mid, end[1]] → end` for horizontal-first routes

### Explicit vs. Automatic Routing Behavior

Archify distinguishes between **authoritative explicit routes** and **heuristic automatic routes**:

| Route Type | Behavior | Use Case |
|------------|----------|----------|
| `orthogonal-h` | Forces horizontal-first L-shape regardless of obstacles | Predictable left-to-right or right-to-left diagrams |
| `orthogonal-v` | Forces vertical-first L-shape regardless of obstacles | Top-to-bottom or bottom-to-top hierarchy |
| `straight` | Direct line with no intermediate points | Simple, uncluttered connections |
| `auto` (default) | Applies collision-aware heuristics, may choose orthogonal or straight | Maximum flexibility, minimal configuration |

The automatic routing logic (lines 24–104 in `render-architecture.mjs`) first checks if anchors are "orthogonal-friendly" using the condition `deltaX < 4 || deltaY < 4`. When this threshold is not met, the *port-rhythm* heuristic attempts to create a clearance-respecting dogleg before falling back to simpler strategies.

## Schema Enforcement and Valid Route Values

The JSON IR schema in [`archify/schemas/architecture.schema.json`](https://github.com/tt-a1i/archify/blob/main/archify/schemas/architecture.schema.json) strictly limits the `route` property to four allowed values. This guarantees that any diagram requesting orthogonal routing will be validated before rendering:

```json
{
  "from": "gateway",
  "to": "api_a",
  "label": "VPC route",
  "variant": "emphasis",
  "route": "orthogonal-h",
  "labelAt": [594, 275]
}

```

Attempting to use an unrecognized route value will trigger a schema validation error, preventing runtime failures in the rendering pipeline.

## Collision Detection and Route Validation

After `routeVia` produces candidate points, Archify validates the route using helper predicates implemented in the same module:

- **`routeHonorsEndpointSides`** — ensures the path enters and exits anchors from the correct cardinal direction
- **`routeClearsComponents`** — checks that no segment intersects any component rectangle

If an orthogonal dogleg would intersect another component, the algorithm attempts the alternative orientation (`orthogonal-v` ↔ `orthogonal-h`). When both candidates fail, Archify returns a deterministic best-effort route (`sideSafe[0]` or `sideAware[0]`) rather than failing silently. This behavior enables the validation stage to surface precise "obstacle" errors for manual diagram adjustment.

## Practical Examples: Configuring Orthogonal Routes

### Horizontal-First Connection

Use `orthogonal-h` when you want the connection to run horizontally before turning:

```js
{
  "from": "gateway",
  "to": "api_a",
  "label": "VPC route",
  "variant": "emphasis",
  "route": "orthogonal-h",
  "labelAt": [594, 275]
}

```

### Vertical-First Connection

Use `orthogonal-v` for top-down or bottom-up hierarchical relationships:

```js
{
  "from": "postgres",
  "to": "replica",
  "label": "cross‑region WAL",
  "variant": "security",
  "route": "orthogonal-v",
  "labelAt": [1003, 529]
}

```

### Automatic Routing Without Explicit Direction

Omit the `route` field to let Archify select the safest path:

```js
{
  "from": "worker",
  "to": "observability",
  "label": "OTLP",
  "variant": "dashed"
}

```

## Testing and Verification

The Archify test suite verifies orthogonal routing behavior through multiple test files:

- **`archify/test/layout-rules.test.mjs`** — asserts that explicit orthogonal routes remain authoritative and are not overridden by automatic heuristics
- **`archify/test/workflow-compiler.test.mjs`** — validates that generated segments are truly axis-aligned using the assertion `segment must be orthogonal`

These tests ensure that the `midX` and `midY` calculations produce mathematically correct L-shapes and that no diagonal segments are introduced inadvertently.

## Summary

- Archify implements orthogonal connection routing through the `routeVia` function in `render-architecture.mjs`, which computes axis-aligned midpoints for L-shaped paths
- Two explicit modes exist: `orthogonal-h` (horizontal-first) and `orthogonal-v` (vertical-first), both producing deterministic two-point polylines
- The JSON schema in [`architecture.schema.json`](https://github.com/tt-a1i/archify/blob/main/architecture.schema.json) enforces valid route values, preventing invalid configurations
- Collision detection via `routeClearsComponents` and `routeHonorsEndpointSides` ensures orthogonal paths respect component boundaries
- Deterministic fallback behavior guarantees reproducible diagrams even when ideal routes are blocked

## Frequently Asked Questions

### What is the difference between orthogonal-h and orthogonal-v in Archify?

**`orthogonal-h`** computes the midpoint between start and end X coordinates, creating a path that travels horizontally first, then vertically—resulting in a right-angle turn. **`orthogonal-v`** uses the Y-coordinate midpoint instead, producing a vertical-first path. Both generate exactly two intermediate points, but the turn direction differs based on which axis gets priority.

### Can Archify automatically choose between horizontal and vertical orthogonal routing?

Yes, when `route` is omitted or set to `auto`, Archify's automatic routing heuristics (lines 24–104) evaluate whether `deltaX < 4 || deltaY < 4` to determine orthogonal-friendliness. The engine then attempts port-rhythm logic and collision-aware doglegs, potentially selecting either orientation or falling back to straight lines based on component placement.

### What happens if an orthogonal route would cross another component?

The algorithm first tries the alternative orthogonal orientation (swapping horizontal-first for vertical-first). If both are blocked, Archify returns a best-effort route from `sideSafe[0]` or `sideAware[0]` and surfaces an obstacle error during validation. This ensures deterministic rendering and clear diagnostic messages rather than silent path degradation.

### Where is the orthogonal routing logic tested?

Unit tests in `archify/test/layout-rules.test.mjs` verify that explicit orthogonal routes take precedence over automatic heuristics, while `archify/test/workflow-compiler.test.mjs` validates axis alignment of generated segments. The [`examples/production-deployment.architecture.json`](https://github.com/tt-a1i/archify/blob/main/examples/production-deployment.architecture.json) file demonstrates real-world usage of both routing modes.