Files
diagrams-drawio/references/routing-best-practices.md
T

19 KiB
Raw Blame History

diagrams-drawio — Connector Routing Best Practices

Connector Routing Best Practices (Zero-Overlap Guarantee)

Complex architecture diagrams with many connectors require deliberate routing. Follow this process to achieve zero connector-shape overlaps.

1. Plan corridors before drawing

Before placing any connectors, identify clear corridors — horizontal or vertical bands on the canvas that are free of all shapes. Route every connector through these corridors.

Vertical corridors (x-axis lanes between columns)

Between each column of shapes, choose a single x-coordinate that lies in the gap:

GAP = (right_edge_of_left_column + left_edge_of_right_column) / 2

Examples from a typical IBM Cloud deployment diagram:

Corridor name x value Description
GAP_AB 370 Between Internet zone and IBM Cloud boundary
GAP_BC 720 Between IBM edge services and VPC
GAP_NS 1510 Between namespace columns inside VPC
GAP_CD 2450 Between VPC right edge and external service group
GAP_DE 2760 Between two external service columns

Horizontal corridors (y-axis lanes between rows)

Between each row of shapes, choose a y-coordinate in the clear gap:

Corridor name y value Description
Y_TOP 110 Above all shapes (highway for cross-diagram connectors)
Y_ROKS 350 Between ingress row and pod row
Y_GW_CORE 640 Between gateway namespace and core namespace
Y_CICD 875 Between ops pods and CI/CD row
Y_BETWEEN 985 Between CI/CD and database row
Y_BELOW 1200 Below all shapes

Rule: When two rows are only 20–40 px apart, the corridor between them is still usable — just ensure the chosen y does not touch any shape's bounding box (see tolerance rule below).

2. Calculate absolute canvas coordinates

draw.io uses relative coordinates for nested containers: a child's x/y is relative to its parent container's top-left corner, not to the canvas. To verify that a connector waypoint (which uses canvas-absolute coordinates) clears a shape, compute:

abs_x = shape.x + parent.x + grandparent.x + ...  (sum all ancestor x offsets)
abs_y = shape.y + parent.y + grandparent.y + ...  (sum all ancestor y offsets)

For swimlane containers, child coordinates are relative to the swimlane's top-left origin (not to the content area below the header). startSize only affects the visual header height — ignore it when computing absolute coordinates.

Build a flat list of all shapes with absolute bounding boxes before routing:

shapes = [
    # (id, abs_x1, abs_y1, abs_x2, abs_y2)
    ("pod-api", 985, 416, 1145, 574),
    ("pod-svc", 810, 416, 967, 574),
    ...
]

3. Verify routes with Python before writing XML

Run an overlap-detection simulation against all shapes before finalising the XML. This prevents invisible bugs that only become apparent when the file is opened.

TOL = 2  # pixels — allow connectors to touch but not overlap interiors

def segment_overlaps_shape(seg, shape):
    sx1, sy1, sx2, sy2 = shape
    if seg['type'] == 'H':  # horizontal segment at y=Y from xA to xB
        Y, xA, xB = seg['y'], min(seg['x1'], seg['x2']), max(seg['x1'], seg['x2'])
        if sy1 + TOL < Y < sy2 - TOL:
            if max(xA, sx1 + TOL) < min(xB, sx2 - TOL):
                return True
    elif seg['type'] == 'V':  # vertical segment at x=X from yA to yB
        X, yA, yB = seg['x'], min(seg['y1'], seg['y2']), max(seg['y1'], seg['y2'])
        if sx1 + TOL < X < sx2 - TOL:
            if max(yA, sy1 + TOL) < min(yB, sy2 - TOL):
                return True
    return False

def route_overlaps(segments, shapes):
    for seg in segments:
        for shape in shapes:
            if segment_overlaps_shape(seg, shape[1:]):  # skip id
                return shape[0], seg
    return None

Convert every connector's waypoint list into a series of H/V segments, then call route_overlaps for each connector. Fix any reported overlap before writing the XML.

Endpoint-touch rule: A connector that terminates at a target shape will appear to overlap that shape in the algorithm because the last segment enters the shape's bounding box. This is expected and correct — exclude the terminal shape (source or target) when checking a connector's first and last segments.

4. Common routing patterns

Pattern A — Top highway for long cross-diagram connectors

Route connectors that must span the full diagram width through Y_TOP (well above all shapes):

source_mid_y → vertical up to Y_TOP → horizontal across to target_col_x → vertical down to target_mid_y

Waypoints example (mxGraphModel format):

<Array as="points">
  <mxPoint x="200" y="110"/>
  <mxPoint x="2600" y="110"/>
</Array>

Pattern B — Stacked services (approach from the left)

When multiple services are stacked vertically in a column (e.g., Watson/AI services), never route a vertical connector through the column. Instead, approach each service individually from a horizontal corridor to its left:

source → vertical to Y_TOP → horizontal to GAP_CD (just left of the column) → horizontal at service_mid_y → connect to service left edge

Each service in the stack gets its own connector that stops at the gap corridor. draw.io completes the final short horizontal stub automatically.

for svc_id, svc_abs_y in stacked_services:
    svc_mid_y = svc_abs_y + svc_height / 2
    waypoints = [
        (source_mid_x, Y_TOP),    # exit source upward
        (GAP_CD, Y_TOP),           # travel across at top highway
        (GAP_CD, svc_mid_y),       # descend to service's row
        # last waypoint stops at corridor; draw.io connects to service edge
    ]

Pattern C — Narrow inter-pod corridors

When adjacent pods in a row leave only a small gap (e.g., pod_A right=967, pod_B left=985 → 18 px gap), that gap is still a usable vertical corridor:

corridor_x = (pod_A_right + pod_B_left) / 2  →  e.g., 976

Use this narrow corridor to route a vertical segment that exits a pod row and connects to shapes above or below:

pod_interior → horizontal to corridor_x → vertical through gap to target_y → horizontal to target

Pattern D — Right bypass for connections below a dense pod grid

When many pods span horizontally across the diagram, route connectors that must reach shapes below by going around the right edge of the pod grid:

source_mid → horizontal right to RIGHT_BYPASS (just right of all pods) → vertical to target_y → horizontal left to target

Set RIGHT_BYPASS to (rightmost_pod_right + left_edge_of_next_column) / 2.

5. Waypoint XML format

Always use the Array as="points" form inside mxGeometry:

<mxCell id="conn-1" value="" style="edgeStyle=orthogonalEdgeStyle;html=1;rounded=1;endArrow=open;endFill=0;" edge="1" source="A" target="B" parent="1">
  <mxGeometry relative="1" as="geometry">
    <Array as="points">
      <mxPoint x="450" y="110"/>
      <mxPoint x="2450" y="110"/>
      <mxPoint x="2450" y="520"/>
    </Array>
  </mxGeometry>
</mxCell>

Rules:

  • All waypoint coordinates are canvas-absolute (not relative to any container).
  • Edges/connectors must be children of the root layer (parent="1"), never children of a container shape.
  • The first waypoint is where draw.io exits the source shape's auto-routing; the last waypoint is where it enters the target.
  • Stop the last waypoint at the corridor boundary — do not pass a waypoint into the interior of the target shape. draw.io will complete the stub automatically.

CRITICAL — Never use port pin constraints on edges

DO NOT add exitX, exitY, exitDx, exitDy, entryX, entryY, entryDx, entryDy attributes to edge mxCell elements.

Indicator Cause Meaning
🔵 Blue circle at connector endpoint source/target IDs set, no port pins Correct — properly connected to shape
🟢 Green circle with white X at connector endpoint Port pin constraints (exitX/Y, entryX/Y) present Wrong — draw.io treats endpoint as floating/unlinked

Port pin attributes force draw.io to attach the connector to a precise computed point on the shape boundary. When the waypoints don't exactly match that computed point, draw.io renders the endpoint as floating (green X). This breaks visual connectivity even though the source/target IDs are set.

Correct pattern — source/target IDs + waypoints only, NO port pins:

<!-- ✅ CORRECT — blue circle, properly connected -->
<mxCell id="edge-001" value="" style="edgeStyle=orthogonalEdgeStyle;html=1;rounded=1;endArrow=open;endFill=0;"
        edge="1" source="shape-A" target="shape-B" parent="1">
  <mxGeometry relative="1" as="geometry">
    <Array as="points">
      <mxPoint x="200" y="420"/>
      <mxPoint x="200" y="200"/>
    </Array>
  </mxGeometry>
</mxCell>

<!-- ❌ WRONG — green X, floating endpoint -->
<mxCell id="edge-001" value="" style="edgeStyle=orthogonalEdgeStyle;html=1;rounded=1;endArrow=open;endFill=0;
        exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;"
        edge="1" source="shape-A" target="shape-B" parent="1">
  ...
</mxCell>

draw.io auto-computes the connection point from source/target shape IDs and the last waypoint direction. Waypoints guide the routing corridor; the actual attachment to the shape is handled automatically.

For «include» / «extend» labels: use real UTF-8 characters «include» / «extend» in the edge value attribute — not XML entities (&#171;include&#187;).

Single-port rule: When multiple edges enter the same target shape, all their last waypoints must approach from the same axis direction (all from left, all from right, all from below, etc.). Mixed directions cause singlePortViolation in page-connectors-validation.

6. Corridor-first layout checklist

Before placing shapes, plan the layout so corridors are naturally available:

  • Leave ≥ 40 px horizontal gaps between columns of shapes
  • Leave ≥ 30 px vertical gaps between rows of shapes
  • Reserve at least one wide horizontal corridor above all shapes (Y_TOP)
  • Reserve at least one wide horizontal corridor below all shapes (Y_BELOW)
  • Do not place shapes in the corridor bands — treat corridors as sacred routing lanes
  • For stacked service columns, leave a vertical corridor to their left at GAP_CD
  • Run Python overlap verification before finalising; fix every reported overlap
  • Apply endpoint-touch exclusion when the last segment enters the target shape

Swimlane / Multi-Zone Diagram Routing

When a diagram uses swimlane zones (horizontal bands, each a swimlane container), apply the following rules in addition to the general patterns above.

Zone layout reference

For a typical layered architecture with startSize=40 swimlanes and 40pt spacing:

zone.y                        ← swimlane top edge
zone.y + 40                   ← header bottom (label occupies y..y+40)
zone.y + 40 + 40 = zone.y+80  ← first child row top (rel y=80 inside container)
zone.y + 80 + child_h         ← first child row bottom
...
zone.y + height               ← swimlane bottom edge

Inter-zone gaps (between adjacent swimlanes) are clean horizontal corridors — use their midpoint as the H-travel y-coordinate for connectors crossing zone boundaries.

Bypass corridors

Always reserve two vertical bypass corridors outside all zones:

Corridor x value Rule
LEFT bypass zone.x - 20 (e.g. x=60 when zones start at x=80) All leftward cross-zone connectors
RIGHT bypass zone.x + zone.width + 20 (e.g. x=1260 when zones end at x=1240) All rightward cross-zone connectors

These bypass corridors run the full canvas height and are free of all shapes. Every connector that must travel between zones should route through one of these corridors.

Multi-row swimlane: horizontal segment placement

When a swimlane has two rows of shapes (row1 and row2), each row has a y-range. Never place a connector H segment at a y-value that falls inside a row's y-range — that will overlap sibling shapes.

Use only these safe H corridors inside a multi-row services swimlane:

Corridor y value When to use
Inter-row gap row1_bottom + (row2_top - row1_bottom)/2 H travel between row1 and row2 shapes
Services-bottom gap row2_bottom + (zone_bottom - row2_bottom)/2 H travel below row2, still inside zone
Inter-zone gaps midpoint of gap between adjacent zones H travel outside zones

Example — services-zone: startSize=40, zone.y=500, row1 abs y=580..620, row2 abs y=660..700, zone bottom=740:

  • Inter-row gap corridor: y=640 (midpoint of y=620..660)
  • Services-bottom corridor: y=720 (midpoint of y=700..740)

Connector routing rules for multi-row swimlanes

Rule 1 — Never route H segments through a row's y-range. If a connector must travel horizontally through the services zone, use y=640 (inter-row) or y=720 (services-bottom), never y=580..620 or y=660..700.

Rule 2 — When exiting a shape in row2 that has sibling shapes to its right in the same row: Do NOT exit from the bottom of the shape and then travel H at y=720 (services-bottom) to the right — this H will cross the V stubs of right-side siblings that exit to the same corridor.

Fix options:

  • a) Exit from the right side of the shape → immediately go to RIGHT bypass x=1260 → V down/up to target (no H inside zone)
  • b) If right-side exit H would cross a sibling shape body: exit right → first waypoint in the column gap to the right (e.g. x=1060 for col5/col6 gap) → V down to services-bottom corridor y=720 → H right to RIGHT bypass → V to target

Rule 3 — Left bypass for connectors going downward to lower zones. When a row2 shape must connect to a shape in a lower zone (messaging, data), route:

shape_bottom → inter-row corridor y=640 → H LEFT to x=LEFT_BYPASS → V down to target zone corridor → H right to target

This ensures the H segment travels in the clear inter-row gap corridor and never crosses sibling shapes.

Rule 4 — connectorShapeOverlaps with zone containers are structural and unavoidable. Any connector crossing a swimlane zone boundary will be flagged as connector_shape_overlap with the zone container. This is expected and acceptable — focus on eliminating connectorCrossings (two connectors intersecting each other) and overlaps with non-container leaf shapes.

Pattern F — Multi-row swimlane fan-out (api-gateway → many services)

When a shape in an upper zone connects to N shapes spread across multiple columns of a multi-row services swimlane:

api-gateway_bottom → H to LEFT_BYPASS at inter-zone gap y → V down LEFT_BYPASS →
  branch per target:
    - col1 (leftmost): H right from LEFT_BYPASS to target_center_x at inter-row gap y
    - col2: same, longer H
    - col3..colN: same pattern, extending H further right
    - for row2 targets: V from inter-row corridor down to row2 top, enter from top

All H branches travel at the same y (inter-row gap) — they are parallel, not crossing.

Pattern G — Event bus → services (right bypass fan-in)

When an event bus (bottom of diagram) connects back up to multiple services:

event-bus_right → H right to RIGHT_BYPASS → V up →
  branch per target:
    - service in row1: H left from RIGHT_BYPASS at row1_center_y to target
    - service in row2: stop at services-bottom corridor y=720 → H left → V up 20pt to target bottom
    - stagger y values slightly (e.g. y=720 for one, y=730 for another) to avoid parallel confusion

Critical: The H segments going LEFT from RIGHT_BYPASS at y=720/730 will cross V stubs of row2 services that exit their bottoms and route DOWN and RIGHT to the right bypass. To avoid these crossings:

  • Route those downward connectors via the LEFT bypass instead (Pattern F inverse)
  • OR ensure the rightward services exit via their right side (not bottom), so no V stub exists at y=720..730

Validation workflow for swimlane diagrams

  1. Run page-connectors-validation after every edit
  2. Fix connectorCrossings first — these are always avoidable
  3. Fix connectorShapeOverlaps with leaf shapes (non-containers) — these are overlaps with actual service boxes
  4. Accept connectorShapeOverlaps with zone containers as structural (unavoidable)
  5. Fix cornerPortViolations, headerEdgeViolations, singlePortViolations — all should reach 0
  6. Target: connectorCrossings=0, cornerPortViolations=0, headerEdgeViolations=0, singlePortViolations=0

Section 8 — Text-width estimation for negative space calculation

When computing negative space manually (e.g. generating a negative-space diagram), shape bounding boxes alone overestimate occupied space. Text labels only occupy a sub-region within the shape bbox. Use the following formula:

charWidth  = fontSize × 0.6           // avg glyph width for proportional fonts
rawWidth   = longestLineCharCount × charWidth
padding    = fontSize × 1.0           // horizontal padding (~0.5em each side)
textWidth  = rawWidth + padding

fontStyle modifiers (draw.io bitmask):
  bit 0 (value 1) = bold   → charWidth × 1.10
  bit 1 (value 2) = italic → charWidth × 1.05

textXMin = clamp(shapeCenterX − textWidth/2, shape.xMin, shape.xMax)
textXMax = clamp(shapeCenterX + textWidth/2, shape.xMin, shape.xMax)
textFlankLeft  = textXMin − shape.xMin   // free space left of text inside bbox
textFlankRight = shape.xMax − textXMax   // free space right of text inside bbox

When to apply:

  • Swimlane headers (startSize=40 band): header text is centered in the full zone width → use text region for occupied X, flanks are free negative space
  • Large container shapes whose children don't fill the full width
  • Any shape where textWidth < shapeWidth — the flanks inside the bbox are free

Example — Marketplace diagram zone headers, fontSize=12 bold (fontStyle=1), center x=660, zone x=80..1240:

Label longestLine chars textWidth textXMin textXMax flank each side
"Client Layer" 12 107 607 713 ~527pt
"API Gateway / Edge Layer" 24 202 559 761 ~479pt
"Core Microservices" 18 155 583 737 ~503pt
"Messaging / Event Bus" 21 178 571 749 ~491pt
"Data Layer" 10 91 615 705 ~535pt

page-negative-space-summary action outputs (per shape):

  • textXMin, textXMax, textWidth — estimated text rendering region
  • textFlankLeft, textFlankRight — free flanks inside bbox
  • rows[].textAwareFreeCorridors — corridors computed using text regions (wider than bbox-based)

When drawing a negative-space diagram: see negative-space-diagram.md for all rules, construction steps, XML pattern, file naming, and validation.