ZAP Protocol

Transports

Network transport layers available in ZAP Protocol

Transports

ZAP Protocol supports multiple transport layers, each optimized for different use cases. The transport abstraction allows switching between them without changing application code.

Transport Overview

TransportProtocolReliableOrderedLatencyUse Case
TCPTCPYesYesLowDefault, general purpose
UDPUDPNoNoLowestTelemetry, real-time
UnixUnix SocketYesYesLowestSame-host IPC
WebSocketWS/WSSYesYesMediumBrowser clients

TCP Transport

TCP is the default transport, providing reliable, ordered delivery.

Configuration

// Server
server := zap.NewServer(
    zap.WithTransport(zap.TCP),
    zap.WithAddress(":9000"),
    zap.WithTCPKeepAlive(30*time.Second),
    zap.WithTCPNoDelay(true),
)

// Client
client, err := zap.Dial("tcp://localhost:9000",
    zap.WithTCPKeepAlive(30*time.Second),
    zap.WithConnectTimeout(5*time.Second),
)

Connection Pooling

TCP connections are automatically pooled:

client, err := zap.Dial("tcp://localhost:9000",
    zap.WithPoolSize(20),              // Max connections
    zap.WithPoolIdleTimeout(60*time.Second),
    zap.WithPoolHealthCheck(true),
)

TLS Configuration

Enable TLS for secure connections:

// Server with TLS
server := zap.NewServer(
    zap.WithTLS(zap.TLSConfig{
        CertFile: "/path/to/cert.pem",
        KeyFile:  "/path/to/key.pem",
        ClientCA: "/path/to/ca.pem",  // Optional: mTLS
    }),
)

// Client with TLS
client, err := zap.Dial("tls://localhost:9000",
    zap.WithTLSConfig(&tls.Config{
        RootCAs: certPool,
    }),
)

UDP Transport

UDP provides lowest latency for fire-and-forget messages.

When to Use UDP

  • Real-time telemetry where occasional loss is acceptable
  • High-frequency metrics collection
  • Game state updates
  • Sensor data streams

Configuration

// Server
server := zap.NewServer(
    zap.WithTransport(zap.UDP),
    zap.WithAddress(":9000"),
    zap.WithUDPBufferSize(65535),
)

// Client
client, err := zap.Dial("udp://localhost:9000",
    zap.WithUDPBufferSize(65535),
)

Reliability Options

For UDP with optional reliability:

client, err := zap.Dial("udp://localhost:9000",
    zap.WithUDPReliable(zap.UDPReliableConfig{
        RetryCount:    3,
        RetryInterval: 100*time.Millisecond,
        AckTimeout:    500*time.Millisecond,
    }),
)

Message Size Limits

UDP messages are limited by MTU (typically 1500 bytes minus headers). ZAP handles fragmentation:

server := zap.NewServer(
    zap.WithTransport(zap.UDP),
    zap.WithUDPFragmentation(true),   // Enable for large messages
    zap.WithUDPMaxMessageSize(65535),
)

Unix Socket Transport

Unix sockets provide the lowest latency for same-host communication.

When to Use Unix Sockets

  • Microservices on the same host
  • Sidecar patterns (service mesh)
  • Container-to-container communication
  • Security-sensitive IPC (filesystem permissions)

Configuration

// Server
server := zap.NewServer(
    zap.WithTransport(zap.Unix),
    zap.WithAddress("/var/run/zap.sock"),
    zap.WithUnixPermissions(0660),
)

// Client
client, err := zap.Dial("unix:///var/run/zap.sock")

Abstract Sockets (Linux)

Use abstract sockets to avoid filesystem:

// Abstract socket (Linux only)
server := zap.NewServer(
    zap.WithAddress("@zap-service"),  // @ prefix = abstract
)

Cleanup

Unix sockets persist on disk. Handle cleanup:

server := zap.NewServer(
    zap.WithAddress("/var/run/zap.sock"),
    zap.WithUnixCleanup(true),  // Remove on shutdown
)

// Or manual cleanup
defer os.Remove("/var/run/zap.sock")

WebSocket Transport

WebSocket enables browser clients to use ZAP services.

When to Use WebSocket

  • Browser-based applications
  • Real-time web dashboards
  • Mobile web apps
  • Cross-origin requirements

Server Configuration

server := zap.NewServer(
    zap.WithTransport(zap.WebSocket),
    zap.WithAddress(":9000"),
    zap.WithWebSocketPath("/rpc"),
    zap.WithWebSocketOrigins([]string{
        "https://app.example.com",
        "https://dashboard.example.com",
    }),
)

Client Configuration (Browser)

import { createClient } from '@zap-protocol/client';

const client = await createClient('ws://localhost:9000/rpc', {
  reconnect: true,
  reconnectInterval: 1000,
  reconnectMaxAttempts: 10,
});

Client Configuration (Go)

client, err := zap.Dial("ws://localhost:9000/rpc",
    zap.WithWebSocketHeaders(http.Header{
        "Authorization": []string{"Bearer token"},
    }),
)

Secure WebSocket (WSS)

// Server
server := zap.NewServer(
    zap.WithTransport(zap.WebSocket),
    zap.WithTLS(zap.TLSConfig{
        CertFile: "/path/to/cert.pem",
        KeyFile:  "/path/to/key.pem",
    }),
)

// Client
client, err := zap.Dial("wss://example.com/rpc")

Multi-Transport Server

Run a single server on multiple transports:

server := zap.NewServer()

// Register your services
server.Register(&myService{})

// Listen on multiple transports
go server.ListenTCP(":9000")
go server.ListenUnix("/var/run/zap.sock")
go server.ListenWebSocket(":9001", "/rpc")

// Wait for shutdown
<-ctx.Done()
server.Shutdown()

Transport Selection

Decision Matrix

RequirementRecommended Transport
General purposeTCP
Maximum performance (same host)Unix
Browser clientsWebSocket
Fire-and-forget telemetryUDP
Secure external connectionsTCP + TLS

Automatic Failover

Configure fallback transports:

client, err := zap.Dial("tcp://localhost:9000",
    zap.WithFallback([]string{
        "unix:///var/run/zap.sock",
        "ws://localhost:9001/rpc",
    }),
    zap.WithFallbackTimeout(5*time.Second),
)

Performance Tuning

Buffer Sizes

server := zap.NewServer(
    zap.WithReadBufferSize(32*1024),   // 32KB read buffer
    zap.WithWriteBufferSize(32*1024),  // 32KB write buffer
)

Concurrency

server := zap.NewServer(
    zap.WithMaxConnections(10000),
    zap.WithMaxConcurrentStreams(100),
)

Timeouts

client, err := zap.Dial("tcp://localhost:9000",
    zap.WithConnectTimeout(5*time.Second),
    zap.WithReadTimeout(30*time.Second),
    zap.WithWriteTimeout(30*time.Second),
    zap.WithIdleTimeout(60*time.Second),
)

Monitoring

Metrics

All transports expose Prometheus metrics:

# Connection metrics
zap_transport_connections_active{transport="tcp"}
zap_transport_connections_total{transport="tcp"}

# Throughput
zap_transport_bytes_sent_total{transport="tcp"}
zap_transport_bytes_received_total{transport="tcp"}

# Latency
zap_transport_latency_seconds{transport="tcp",quantile="0.99"}

Health Checks

server := zap.NewServer(
    zap.WithHealthCheck("/health"),
)

Next Steps

On this page