Skip to main content

Overview

Gateways and leaf nodes solve different connectivity challenges in NATS deployments:
  • Gateways: Connect multiple NATS clusters into a super-cluster for geo-distribution
  • Leaf nodes: Extend NATS clusters with hub-and-spoke connections for edge computing
Both provide alternatives to full mesh clustering when network topology, geography, or scale make full mesh impractical.

Gateways

Gateways connect separate NATS clusters across regions or data centers without the overhead of full mesh routes.

Gateway Concept

A gateway connection:
  • Links two named clusters
  • Exchanges subscription interest between clusters
  • Forwards messages only when interest exists
  • Operates at the cluster level, not server level
  • Optimizes for wide-area network efficiency

Super-Cluster Architecture

From server/gateway.go:35-59, gateways implement:
  • Interest-based routing: Messages only cross gateways when subscribers exist
  • Optimistic mode: Initially assumes interest until told otherwise
  • Interest-only mode: Explicit interest tracking for efficiency
  • Transitioning mode: Automatic mode switching based on traffic patterns

Gateway Interest Modes

From server/gateway.go:93-111:
type GatewayInterestMode byte

const (
    Optimistic     // Send unless no interest
    Transitioning  // Switching to interest-only
    InterestOnly   // Only send with explicit interest
)
Optimistic mode (default):
  • Cluster sends messages across gateway unless explicitly told no interest
  • Efficient when most subjects have remote subscribers
  • Remote sends “no interest” messages to suppress traffic
Interest-only mode:
  • Cluster only sends messages with explicit remote interest
  • Efficient when few subjects have remote subscribers
  • Requires full interest propagation
Transitioning:
  • Triggered after too many “no interest” messages (default: 1000)
  • Cluster switches to interest-only mode
  • Prevents excessive unnecessary traffic

Gateway Configuration

Basic gateway setup:
gateway {
  name: "us-west"
  listen: "0.0.0.0:7222"
  
  gateways: [
    {
      name: "us-east"
      urls: [
        "nats://gateway1.us-east.example.com:7222"
        "nats://gateway2.us-east.example.com:7222"
      ]
    }
    {
      name: "eu-west"
      urls: [
        "nats://gateway1.eu-west.example.com:7222"
      ]
    }
  ]
}

Gateway TLS

Secure gateway connections:
gateway {
  name: "us-west"
  listen: "0.0.0.0:7222"
  
  tls {
    cert_file: "./certs/gateway-cert.pem"
    key_file: "./certs/gateway-key.pem"
    ca_file: "./certs/ca.pem"
    verify: true
  }
  
  gateways: [...]
}
From server/gateway.go:71, when TLS verify is disabled, certificate chains are not validated. Never use in production.

Gateway Protocol Details

From server/gateway.go:87-91, gateway commands:
  • gatewayCmdGossip: Share gateway topology
  • gatewayCmdAllSubsStart: Begin full interest sync
  • gatewayCmdAllSubsComplete: Finish interest sync
Gateways exchange INFO messages containing:
  • Gateway name and URLs
  • Cluster information
  • Interest mode settings
  • Protocol capabilities

Reply Subject Handling

Gateways use special reply subject prefixes from server/gateway.go:43-54:
  • Old format: $GR.<hash>.<subject>
  • New format: _GR_.<cluster_hash>.<server_hash>.<subject>
This ensures reply messages route back through the correct gateway to the requesting client.

Use Cases for Gateways

Geographic Distribution

Deploy clusters in multiple regions:
Cluster US-WEST (3 servers) <--gateway--> Cluster US-EAST (3 servers)
                                                      ^
                                                      |
                                                   gateway
                                                      |
                                                      v
                                          Cluster EU-WEST (3 servers)
  • Each region has a local cluster (low latency)
  • Gateways connect regions (high latency tolerant)
  • Clients connect to local cluster
  • Messages reach subscribers in any region

Failover Between Regions

Gateways enable cross-region failover:
  1. Client connects to local cluster
  2. Local cluster fails
  3. Client reconnects to remote cluster via gateway
  4. Application continues without message loss

Data Sovereignty

Control message flow between regions:
  • Use accounts to isolate sensitive data
  • Configure imports/exports to control cross-region flow
  • Messages only cross gateways when explicitly allowed

Cost Optimization

Reduce cross-region traffic costs:
  • Interest-only mode minimizes unnecessary traffic
  • Messages only traverse expensive WAN links when needed
  • Local clusters handle regional traffic locally

Leaf Nodes

Leaf nodes extend NATS clusters with lightweight, hub-and-spoke connections.

Leaf Node Concept

A leaf node connection:
  • Connects a server (spoke) to a cluster (hub)
  • Appears as a single client to the hub
  • Supports bidirectional messaging
  • Automatically reconnects to hub cluster
  • Can operate in isolated mode

Hub and Spoke vs Spoke

From server/leafnode.go:121-133:
  • Hub: The server/cluster accepting leaf connections
  • Spoke: The server initiating the leaf connection
  • Solicited: Spoke-initiated outbound connection
  • Unsolicited: Hub-accepted inbound connection

Leaf Node Architecture

Leaf nodes support several patterns: Edge Computing:
     Hub Cluster (3 servers)
       /       |        \
    Edge1    Edge2    Edge3
Each edge location runs a single NATS server connected to the central hub. Department Networks:
  Corporate Cluster
         |
    Department Server
         |
      Employees
Department server connects to corporate cluster but maintains local department isolation. Development/Testing:
  Production Cluster
         |
    Developer Laptop
Developers run local NATS connected to production (read-only) for testing.

Leaf Node Configuration

Hub Configuration

Accept leaf node connections:
leafnodes {
  listen: "0.0.0.0:7422"
  
  authorization {
    users: [
      {user: "leaf1", password: "password1", account: "ACCOUNT1"}
      {user: "leaf2", password: "password2", account: "ACCOUNT2"}
    ]
  }
}

Spoke Configuration

Connect to hub:
leafnodes {
  remotes: [
    {
      url: "nats-leaf://leaf1:[email protected]:7422"
      account: "LOCAL_ACCOUNT"
    }
  ]
}

Leaf Node Features

Account Binding

Leaf nodes bind local accounts to remote accounts:
leafnodes {
  remotes: [
    {
      url: "nats-leaf://hub.example.com:7422"
      account: "EDGE_USERS"      # Local account
      credentials: "./leaf.creds" # Maps to hub account
    }
  ]
}
Messages published to EDGE_USERS appear in the hub account.

TLS for Leaf Nodes

Secure leaf connections:
leafnodes {
  remotes: [
    {
      url: "tls://hub.example.com:7422"
      tls {
        cert_file: "./certs/leaf-cert.pem"
        key_file: "./certs/leaf-key.pem"
        ca_file: "./certs/ca.pem"
      }
    }
  ]
}
From server/leafnode.go:47, when TLS verify is disabled, certificates are not validated. Never use in production.

WebSocket Leaf Nodes

Leaf nodes can connect via WebSocket:
leafnodes {
  remotes: [
    {
      url: "wss://hub.example.com/leafnode"
    }
  ]
}
From server/leafnode.go:64, the path /leafnode identifies WebSocket connections as leaf nodes.

Compression

From server/leafnode.go:101, leaf nodes support S2 compression:
leafnodes {
  remotes: [
    {
      url: "nats://hub.example.com:7422"
      compression: "s2_auto"
    }
  ]
}
Particularly useful for bandwidth-constrained edge connections.

Leaf Node Isolation

From server/leafnode.go:86, isolated leaf nodes:
  • Don’t receive subscriptions from other leaf nodes
  • Only see traffic from hub cluster
  • Prevents east-west traffic between leaf nodes
  • Useful for security and performance
Configure isolation:
leafnodes {
  remotes: [
    {
      url: "nats://hub.example.com:7422"
      isolated: true
    }
  ]
}

Loop Detection

From server/leafnode.go:49-60, leaf nodes prevent loops:
  • Loop detection subject: $LDS.<random>
  • If leaf receives its own loop detection message, loop detected
  • Connection closed with 30-second reconnect delay
  • Prevents cluster connecting to itself via leaf

Leaf Node Reconnection

Leaf nodes automatically reconnect with backoff:
  • Multiple hub URLs supported for failover
  • Automatic reconnection on disconnect
  • Subscription state restored on reconnect
  • From server/leafnode.go:50-57, special delays for error conditions:
    • Loop detected: 30 seconds
    • Permission violation: 30 seconds
    • Same cluster name: 30 seconds

Multi-Region Connectivity Patterns

Hybrid: Clusters + Gateways + Leaf Nodes

Combine all three for complex topologies:
Region US:
  Cluster US-WEST (3 servers) <--gateway--> Cluster US-EAST (3 servers)
       ^
       | (leaf)
       |
    Edge Servers (leaf nodes)
  • Regional clusters for low latency
  • Gateways for cross-region
  • Leaf nodes for edge locations

Active-Active Multi-Region

Cluster A <--gateway--> Cluster B <--gateway--> Cluster C
   ^                        ^                        ^
   |                        |                        |
 Clients                 Clients                 Clients
Clients in each region connect locally, messages route via gateways.

Hub with Regional Spokes

         Hub Cluster
         /    |    \
      Leaf  Leaf  Leaf
     EMEA   APAC   AMER
Central hub with regional leaf nodes, all traffic flows through hub.

Configuration Examples from Source

Gateway with Multiple Remotes

From source code patterns:
gateway {
  name: "production-us"
  listen: "0.0.0.0:7222"
  
  # Advertise specific URLs
  advertise: "gateway.prod-us.example.com:7222"
  
  # Connect to other clusters
  gateways: [
    {name: "production-eu", urls: ["nats://gw1.prod-eu.example.com:7222"]}
    {name: "production-ap", urls: ["nats://gw1.prod-ap.example.com:7222"]}
  ]
  
  # Don't accept unknown gateways
  reject_unknown: true
}

Leaf Node with Credentials

leafnodes {
  remotes: [
    {
      urls: [
        "nats://hub1.example.com:7422"
        "nats://hub2.example.com:7422"
        "nats://hub3.example.com:7422"
      ]
      credentials: "/etc/nats/leaf.creds"
      account: "EDGE"
    }
  ]
}

Performance Considerations

Gateway Performance

  • Interest propagation overhead: Interest-only mode trades setup cost for reduced traffic
  • RTT sensitivity: High RTT impacts mode transition decisions
  • Connection pooling: From server/gateway.go:140, gateways maintain ordered connections
  • Ping interval: Max 15 seconds from server/gateway.go:58

Leaf Node Performance

  • Hub cluster impact: Each leaf appears as one client
  • Subject interest: All leaf subscriptions propagated to hub
  • Message amplification: Hub messages reach all leaf subscribers
  • Isolation benefit: Isolated leafs reduce cross-leaf traffic

Best Practices

Gateway Deployment

  1. Name gateways consistently: Use geographic or functional names
  2. Configure all connections: Each cluster should list all other clusters
  3. Use TLS: Encrypt cross-region traffic
  4. Monitor interest modes: Track mode transitions
  5. Set reject_unknown: Prevent unauthorized gateway connections

Leaf Node Deployment

  1. Use credentials: JWT-based authentication preferred
  2. Multiple hub URLs: Configure failover URLs
  3. Account mapping: Plan account topology carefully
  4. Consider isolation: Use for edge security
  5. Compression for WAN: Enable for bandwidth-limited connections

Capacity Planning

  1. Gateway bandwidth: Monitor cross-region traffic
  2. Hub capacity: Each leaf consumes hub resources
  3. Interest churn: Frequent subscriptions trigger interest updates
  4. Subject cardinality: Many unique subjects increase interest state

Troubleshooting

Gateway Issues

Check /gatewayz endpoint:
  • Connection state per gateway
  • Interest mode per account
  • Message and byte counts
  • Number of “no interest” suppressions

Leaf Node Issues

Check /leafz endpoint:
  • Leaf connection status
  • Account bindings
  • Subscription counts
  • RTT and compression stats
Common issues:
  • Loop detection: Check cluster names don’t match
  • Permission errors: Verify account permissions
  • Connection failures: Check network and authentication

Next Steps

Clustering

Understand cluster fundamentals

Accounts

Configure multi-tenancy across gateways and leaf nodes

Build docs developers (and LLMs) love