gRPC Guide

High-performance gRPC APIs for mesh networking, VPN connectivity, and threat intelligence. Protocol Buffers, bidirectional streaming, and sub-millisecond latency.

gRPC + Protocol Buffers

High-Performance gRPC APIs

Protocol Buffer-based RPC services for mesh networking, VPN tunnel management, and threat intelligence. Bidirectional streaming, strong typing, and sub-millisecond overhead.

0
Total RPCs
0
gRPC Services
0
Streaming Patterns
0
Protocol Buffers

Overview

OrbVPN's gRPC APIs are designed for low-latency, high-throughput communication between services. They are the primary protocol for mesh networking (OrbMesh), VPN tunnel management, and real-time threat intelligence streaming.

Protocol Buffers

Strongly typed, binary-serialized messages that are 5-10x smaller than JSON and significantly faster to parse. Proto3 syntax with full backward compatibility.

Bidirectional Streaming

Full support for all four gRPC patterns: unary, server-streaming, client-streaming, and bidirectional streaming. Perfect for real-time metrics and threat feeds.

HTTP/2 Transport

Built on HTTP/2 with multiplexed streams, header compression, and flow control. Multiple RPCs share a single TCP connection.

Code Generation

Generate type-safe client stubs in Go, Python, JavaScript, Java, C++, and 10+ other languages directly from the proto files.


Connection Setup

Three gRPC endpoints serve different parts of the OrbVPN platform.

ServiceAddressTLSAuthentication
OrbNET gRPCgrpc://api.orbai.world:50051TLS 1.3JWT metadata
OrbMesh gRPCPer-server IP:50051mTLSClient certificate
OrbGuard gRPCgrpc://guard.orbai.world:50051TLS 1.3API key metadata

Authentication

Each gRPC service uses a different authentication mechanism, passed as gRPC metadata (equivalent to HTTP headers).

OrbNET -- JWT Metadata

Attach your JWT access token as the authorization metadata key.

import "google.golang.org/grpc/metadata"

md := metadata.Pairs("authorization", "Bearer eyJhbGciOiJIUzI1NiIs...")
ctx := metadata.NewOutgoingContext(context.Background(), md)

resp, err := client.GetUser(ctx, &pb.GetUserRequest{UserId: "usr_abc123"})

OrbGuard -- API Key Metadata

Attach your API key as the x-api-key metadata key.

md := metadata.Pairs("x-api-key", "ogk_live_abc123...")
ctx := metadata.NewOutgoingContext(context.Background(), md)

resp, err := threatClient.CheckIndicator(ctx, &pb.CheckIndicatorRequest{
    Indicator: "suspicious-domain.com",
    Type:      pb.IndicatorType_DOMAIN,
})

OrbMesh -- mTLS (Mutual TLS)

OrbMesh nodes authenticate using client certificates issued by the OrbVPN CA.

import "google.golang.org/grpc/credentials"

creds, err := credentials.NewClientTLSFromFile("ca.pem", "")
// For mTLS, load both client cert and key
tlsCert, err := tls.LoadX509KeyPair("client.pem", "client-key.pem")

tlsConfig := &tls.Config{
    Certificates: []tls.Certificate{tlsCert},
    RootCAs:      certPool,
}

conn, err := grpc.Dial(
    "mesh-node-ip:50051",
    grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
)

Certificate Provisioning

OrbMesh node certificates are provisioned automatically during node registration. See the OrbMesh overview for the full onboarding flow.


Services

1. OrbMeshService

The mesh networking control plane. Manages node registration, health monitoring, topology, and real-time metrics collection across the OrbVPN server fleet.

gRPC

OrbMeshService

Mesh networking control plane for OrbVPN server fleet management, health monitoring, and topology control.

RegisterNode
Unary
Heartbeat
Unary
StreamMetrics
Server Stream
PushMetrics
Client Stream
SyncTopology
Bidirectional
GetNodeStatus
Unary
ListNodes
Unary
DrainNode
Unary
RotateCertificates
Unary
DeregisterNode
Unary

2. VPNService

VPN tunnel lifecycle management. Supports WireGuard, VLESS, and OrbConnect protocols with real-time status streaming.

gRPC

VPNService

VPN tunnel lifecycle management for WireGuard, VLESS, and OrbConnect protocols.

ConnectWireGuard
Unary
ConnectVLESS
Unary
ConnectOrbConnect
Unary
Disconnect
Unary
GetStatus
Unary
StreamStatus
Server Stream

3. ThreatIntelligenceService

Real-time threat detection, indicator checking, and bulk threat analysis from OrbGuard Labs.

gRPC

ThreatIntelligenceService

Threat intelligence and indicator analysis from OrbGuard Labs. Check indicators, stream live threats, and perform bulk analysis.

CheckIndicator
Unary
StreamThreats
Server Stream
BatchCheck
Unary
StreamIndicators
Client Stream
LiveAnalysis
Bidirectional

Key Message Types

RegisterNodeRequest

messageRegisterNodeRequest
#FieldTypeDescription
1
hostnamereq
stringFully qualified hostname of the node.
2
ip_addressreq
stringPublic IP address of the node.
3
regionreq
stringGeographic region code (e.g., us-east-1, eu-west-1).
4
repeatedprotocols
ProtocolList of supported VPN protocols (WIREGUARD, VLESS, ORBCONNECT).
5
capacityreq
NodeCapacityMaximum connection capacity and resource limits for the node.
6
labels
map<string, string>Arbitrary key-value labels for node categorization and routing rules.

ConnectWireGuardRequest

messageConnectWireGuardRequest
#FieldTypeDescription
1
user_idreq
stringAuthenticated user ID.
2
device_idreq
stringUnique device identifier for the connecting client.
3
server_id
stringPreferred server ID. If empty, the control plane selects the optimal server.
4
public_keyreq
bytesWireGuard public key of the client device (32 bytes, Curve25519).
5
preshared_key
bytesOptional WireGuard preshared key for post-quantum resistance (32 bytes).
6
preferred_endpoint
stringPreferred server region or city code for geographic optimization.
7
kill_switch
boolEnable kill switch rules in the server response (block traffic if tunnel drops).

CheckIndicatorRequest

messageCheckIndicatorRequest
#FieldTypeDescription
1
indicatorreq
stringThe indicator value to check (domain, IP address, URL, or file hash).
2
typereq
IndicatorTypeType of indicator: DOMAIN, IP, URL, SHA256, MD5, or SHA1.
3
include_context
boolInclude enrichment context (WHOIS, DNS history, related indicators) in the response.
4
include_yara_matches
boolRun matching YARA rules and include results (only applies to file hash indicators).

ThreatEvent

messageThreatEvent
#FieldTypeDescription
1
idreq
stringUnique event identifier.
2
indicatorreq
stringThe threat indicator (domain, IP, URL, or hash).
3
indicator_typereq
IndicatorTypeType of indicator.
4
severityreq
SeverityThreat severity: INFO, LOW, MEDIUM, HIGH, or CRITICAL.
5
scorereq
int32Threat score from 0 (benign) to 100 (confirmed malicious).
6
repeatedcategories
stringThreat categories: malware, phishing, c2, spam, cryptominer, etc.
7
first_seenreq
google.protobuf.TimestampWhen the indicator was first observed by OrbGuard.
8
last_seenreq
google.protobuf.TimestampWhen the indicator was most recently observed.

Code Examples

Go -- Unary RPC

package main

import (
    "context"
    "fmt"
    "log"

    pb "github.com/orbvpn/proto/orbguard/v1"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
    "google.golang.org/grpc/metadata"
)

func main() {
    // Connect with TLS
    creds, err := credentials.NewClientTLSFromFile("ca.pem", "guard.orbai.world")
    if err != nil {
        log.Fatal(err)
    }

    conn, err := grpc.Dial("guard.orbai.world:50051", grpc.WithTransportCredentials(creds))
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    client := pb.NewThreatIntelligenceServiceClient(conn)

    // Attach API key
    ctx := metadata.AppendToOutgoingContext(
        context.Background(),
        "x-api-key", "ogk_live_abc123...",
    )

    // Check a threat indicator
    resp, err := client.CheckIndicator(ctx, &pb.CheckIndicatorRequest{
        Indicator:      "suspicious-domain.com",
        Type:           pb.IndicatorType_DOMAIN,
        IncludeContext: true,
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Indicator: %s\n", resp.Indicator)
    fmt.Printf("Score:     %d/100\n", resp.Score)
    fmt.Printf("Severity:  %s\n", resp.Severity)
    fmt.Printf("Malicious: %v\n", resp.IsMalicious)

    for _, cat := range resp.Categories {
        fmt.Printf("  Category: %s\n", cat)
    }
}

Go -- Server Streaming

// Stream real-time threat events
stream, err := client.StreamThreats(ctx, &pb.StreamThreatsRequest{
    Severity:   []pb.Severity{pb.Severity_HIGH, pb.Severity_CRITICAL},
    Categories: []string{"malware", "phishing", "c2"},
})
if err != nil {
    log.Fatal(err)
}

for {
    event, err := stream.Recv()
    if err != nil {
        log.Println("Stream ended:", err)
        break
    }

    fmt.Printf("[%s] %s -- %s (score: %d)\n",
        event.Severity,
        event.IndicatorType,
        event.Indicator,
        event.Score,
    )
}

Go -- Bidirectional Streaming

// Bidirectional topology sync with OrbMesh
stream, err := meshClient.SyncTopology(ctx)
if err != nil {
    log.Fatal(err)
}

// Send local topology updates in a goroutine
go func() {
    updates := getLocalTopologyUpdates() // your implementation
    for _, update := range updates {
        if err := stream.Send(&update); err != nil {
            log.Println("Send error:", err)
            return
        }
    }
    stream.CloseSend()
}()

// Receive cluster-wide topology updates
for {
    update, err := stream.Recv()
    if err != nil {
        log.Println("Stream ended:", err)
        break
    }

    fmt.Printf("Topology update: node=%s action=%s\n",
        update.NodeId, update.Action)
    applyTopologyUpdate(update) // your implementation
}

Python -- Unary RPC

import grpc
from orbguard.v1 import threat_service_pb2 as pb
from orbguard.v1 import threat_service_pb2_grpc as pb_grpc

# Connect with TLS
credentials = grpc.ssl_channel_credentials(
    root_certificates=open("ca.pem", "rb").read()
)

channel = grpc.secure_channel("guard.orbai.world:50051", credentials)
client = pb_grpc.ThreatIntelligenceServiceStub(channel)

# Attach API key metadata
metadata = [("x-api-key", "ogk_live_abc123...")]

# Check a threat indicator
response = client.CheckIndicator(
    pb.CheckIndicatorRequest(
        indicator="suspicious-domain.com",
        type=pb.DOMAIN,
        include_context=True,
    ),
    metadata=metadata,
)

print(f"Indicator: {response.indicator}")
print(f"Score:     {response.score}/100")
print(f"Severity:  {pb.Severity.Name(response.severity)}")
print(f"Malicious: {response.is_malicious}")

Python -- Server Streaming

# Stream real-time threats
stream = client.StreamThreats(
    pb.StreamThreatsRequest(
        severity=[pb.HIGH, pb.CRITICAL],
        categories=["malware", "phishing"],
    ),
    metadata=metadata,
)

for event in stream:
    print(f"[{pb.Severity.Name(event.severity)}] "
          f"{pb.IndicatorType.Name(event.indicator_type)}: "
          f"{event.indicator} (score: {event.score})")

Python -- Async Bidirectional Streaming

import asyncio
import grpc.aio

async def live_analysis():
    channel = grpc.aio.secure_channel(
        "guard.orbai.world:50051",
        grpc.ssl_channel_credentials(open("ca.pem", "rb").read()),
    )
    client = pb_grpc.ThreatIntelligenceServiceStub(channel)
    metadata = [("x-api-key", "ogk_live_abc123...")]

    # Bidirectional stream
    async def indicator_generator():
        indicators = [
            ("suspicious-domain.com", pb.DOMAIN),
            ("192.168.1.100", pb.IP),
            ("https://phishing-site.com/login", pb.URL),
        ]
        for indicator, itype in indicators:
            yield pb.AnalysisRequest(indicator=indicator, type=itype)
            await asyncio.sleep(0.1)  # Simulate real-time submissions

    stream = client.LiveAnalysis(indicator_generator(), metadata=metadata)

    async for result in stream:
        print(f"Result: {result.indicator} -> score={result.score}, "
              f"malicious={result.is_malicious}")

asyncio.run(live_analysis())

Streaming Patterns

gRPC supports four communication patterns. OrbVPN uses all four across its services.

Unary

Classic request-response. Client sends one request, server returns one response. Used for CheckIndicator, RegisterNode, ConnectWireGuard.

Server Streaming

Client sends one request, server returns a stream of responses. Used for StreamMetrics, StreamThreats, StreamStatus.

Client Streaming

Client sends a stream of requests, server returns one response. Used for PushMetrics, StreamIndicators.

Bidirectional Streaming

Both client and server send streams of messages independently. Used for SyncTopology, LiveAnalysis.

Pattern Comparison

PatternUse CaseOrbVPN Examples
UnarySingle request, single responseCheckIndicator, RegisterNode, ConnectWireGuard
Server StreamSubscribe to continuous dataStreamMetrics, StreamThreats, StreamStatus
Client StreamPush batch dataPushMetrics, StreamIndicators
BidirectionalReal-time sync, interactive analysisSyncTopology, LiveAnalysis

Proto File References

Download the proto files to generate client stubs in any supported language.

Proto FilePackageDescription
orbmesh/v1/mesh_service.protoorbvpn.mesh.v1OrbMesh control plane -- node management, topology, metrics
orbnet/v1/vpn_service.protoorbvpn.vpn.v1VPN tunnel management -- WireGuard, VLESS, OrbConnect
orbguard/v1/threat_service.protoorbvpn.guard.v1Threat intelligence -- indicators, analysis, streaming
orbvpn/v1/common.protoorbvpn.v1Shared types -- Severity, IndicatorType, Protocol, NodeCapacity

Proto File Access

Proto files are available in the OrbVPN GitHub repository. Clone the repo and use protoc or buf to generate client code in your language.

Generating Client Code

# Using protoc (Go example)
protoc --go_out=. --go-grpc_out=. \
  -I proto/ \
  proto/orbguard/v1/threat_service.proto

# Using buf (recommended)
buf generate proto/

# Using grpc_tools (Python)
python -m grpc_tools.protoc \
  -I proto/ \
  --python_out=. \
  --grpc_python_out=. \
  proto/orbguard/v1/threat_service.proto

Development Tools

grpcurl

Command-line tool for interacting with gRPC servers. Like cURL but for gRPC. Supports reflection, JSON input, and streaming.

Evans

Expressive universal gRPC client with a REPL interface. Great for exploring services interactively with tab completion.

BloomRPC

GUI client for gRPC services. Import proto files, send requests, and inspect responses with a Postman-like interface.

grpcurl Examples

# List available services (requires server reflection)
grpcurl -cacert ca.pem guard.orbai.world:50051 list

# Describe a service
grpcurl -cacert ca.pem guard.orbai.world:50051 \
  describe orbvpn.guard.v1.ThreatIntelligenceService

# Check a threat indicator
grpcurl -cacert ca.pem \
  -H "x-api-key: ogk_live_abc123..." \
  -d '{"indicator": "suspicious-domain.com", "type": "DOMAIN"}' \
  guard.orbai.world:50051 \
  orbvpn.guard.v1.ThreatIntelligenceService/CheckIndicator

# Stream threats (server streaming)
grpcurl -cacert ca.pem \
  -H "x-api-key: ogk_live_abc123..." \
  -d '{"severity": ["HIGH", "CRITICAL"]}' \
  guard.orbai.world:50051 \
  orbvpn.guard.v1.ThreatIntelligenceService/StreamThreats

Error Handling

gRPC uses standard status codes. OrbVPN services return additional error details in the status metadata.

gRPC CodeMeaningCommon Cause
OK (0)Success--
INVALID_ARGUMENT (3)Bad requestMissing or invalid field in the request message
NOT_FOUND (5)Resource missingNode, user, or indicator not found
PERMISSION_DENIED (7)Auth failureInvalid or expired JWT/API key
RESOURCE_EXHAUSTED (8)Rate limitedToo many requests -- retry with backoff
UNAVAILABLE (14)Service downTransient failure -- retry with backoff
UNAUTHENTICATED (16)No credentialsMissing authorization metadata
import (
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)

resp, err := client.CheckIndicator(ctx, req)
if err != nil {
    st, ok := status.FromError(err)
    if ok {
        switch st.Code() {
        case codes.Unauthenticated:
            // Refresh token and retry
        case codes.ResourceExhausted:
            // Rate limited -- backoff and retry
        case codes.Unavailable:
            // Transient failure -- retry with backoff
        default:
            log.Fatalf("gRPC error: %s -- %s", st.Code(), st.Message())
        }
    }
}

Deadline / Timeout

Always set a deadline on your gRPC context. Without a deadline, a stuck RPC can hold resources indefinitely. A 30-second deadline is a good default for unary RPCs. For streaming RPCs, use a longer deadline or implement application-level timeouts.

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

resp, err := client.CheckIndicator(ctx, req)

Performance Tips

Reuse Connections

gRPC connections are multiplexed over a single TCP connection. Create one channel per target and reuse it across all RPCs. Do not create a new connection per request.

Use Streaming for Bulk Ops

Prefer client-streaming or bidirectional RPCs over repeated unary calls for batch operations. StreamIndicators is 10x faster than calling CheckIndicator in a loop.

Set Deadlines

Always set context deadlines. A reasonable default is 30s for unary RPCs and 5m for streaming RPCs. Without deadlines, stuck RPCs leak resources.

Enable Keepalive

Configure gRPC keepalive parameters to prevent idle connections from being closed by intermediate proxies. Set keepalive time to 30s and timeout to 10s.


Build with gRPC

Leverage OrbVPN's high-performance gRPC APIs for mesh networking, VPN tunnel management, and real-time threat intelligence. Strongly typed, blazing fast, and production-ready.

View SDKs