gRPC Guide
High-performance gRPC APIs for mesh networking, VPN connectivity, and threat intelligence. Protocol Buffers, bidirectional streaming, and sub-millisecond latency.
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.
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.
| Service | Address | TLS | Authentication |
|---|---|---|---|
| OrbNET gRPC | grpc://api.orbai.world:50051 | TLS 1.3 | JWT metadata |
| OrbMesh gRPC | Per-server IP:50051 | mTLS | Client certificate |
| OrbGuard gRPC | grpc://guard.orbai.world:50051 | TLS 1.3 | API 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.
OrbMeshService
Mesh networking control plane for OrbVPN server fleet management, health monitoring, and topology control.
RegisterNodeHeartbeatStreamMetricsPushMetricsSyncTopologyGetNodeStatusListNodesDrainNodeRotateCertificatesDeregisterNode2. VPNService
VPN tunnel lifecycle management. Supports WireGuard, VLESS, and OrbConnect protocols with real-time status streaming.
VPNService
VPN tunnel lifecycle management for WireGuard, VLESS, and OrbConnect protocols.
ConnectWireGuardConnectVLESSConnectOrbConnectDisconnectGetStatusStreamStatus3. ThreatIntelligenceService
Real-time threat detection, indicator checking, and bulk threat analysis from OrbGuard Labs.
ThreatIntelligenceService
Threat intelligence and indicator analysis from OrbGuard Labs. Check indicators, stream live threats, and perform bulk analysis.
CheckIndicatorStreamThreatsBatchCheckStreamIndicatorsLiveAnalysisKey Message Types
RegisterNodeRequest
RegisterNodeRequest| # | Field | Type | Description |
|---|---|---|---|
| 1 | hostnamereq | string | Fully qualified hostname of the node. |
| 2 | ip_addressreq | string | Public IP address of the node. |
| 3 | regionreq | string | Geographic region code (e.g., us-east-1, eu-west-1). |
| 4 | repeated protocols | Protocol | List of supported VPN protocols (WIREGUARD, VLESS, ORBCONNECT). |
| 5 | capacityreq | NodeCapacity | Maximum connection capacity and resource limits for the node. |
| 6 | labels | map<string, string> | Arbitrary key-value labels for node categorization and routing rules. |
ConnectWireGuardRequest
ConnectWireGuardRequest| # | Field | Type | Description |
|---|---|---|---|
| 1 | user_idreq | string | Authenticated user ID. |
| 2 | device_idreq | string | Unique device identifier for the connecting client. |
| 3 | server_id | string | Preferred server ID. If empty, the control plane selects the optimal server. |
| 4 | public_keyreq | bytes | WireGuard public key of the client device (32 bytes, Curve25519). |
| 5 | preshared_key | bytes | Optional WireGuard preshared key for post-quantum resistance (32 bytes). |
| 6 | preferred_endpoint | string | Preferred server region or city code for geographic optimization. |
| 7 | kill_switch | bool | Enable kill switch rules in the server response (block traffic if tunnel drops). |
CheckIndicatorRequest
CheckIndicatorRequest| # | Field | Type | Description |
|---|---|---|---|
| 1 | indicatorreq | string | The indicator value to check (domain, IP address, URL, or file hash). |
| 2 | typereq | IndicatorType | Type of indicator: DOMAIN, IP, URL, SHA256, MD5, or SHA1. |
| 3 | include_context | bool | Include enrichment context (WHOIS, DNS history, related indicators) in the response. |
| 4 | include_yara_matches | bool | Run matching YARA rules and include results (only applies to file hash indicators). |
ThreatEvent
ThreatEvent| # | Field | Type | Description |
|---|---|---|---|
| 1 | idreq | string | Unique event identifier. |
| 2 | indicatorreq | string | The threat indicator (domain, IP, URL, or hash). |
| 3 | indicator_typereq | IndicatorType | Type of indicator. |
| 4 | severityreq | Severity | Threat severity: INFO, LOW, MEDIUM, HIGH, or CRITICAL. |
| 5 | scorereq | int32 | Threat score from 0 (benign) to 100 (confirmed malicious). |
| 6 | repeated categories | string | Threat categories: malware, phishing, c2, spam, cryptominer, etc. |
| 7 | first_seenreq | google.protobuf.Timestamp | When the indicator was first observed by OrbGuard. |
| 8 | last_seenreq | google.protobuf.Timestamp | When 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
| Pattern | Use Case | OrbVPN Examples |
|---|---|---|
| Unary | Single request, single response | CheckIndicator, RegisterNode, ConnectWireGuard |
| Server Stream | Subscribe to continuous data | StreamMetrics, StreamThreats, StreamStatus |
| Client Stream | Push batch data | PushMetrics, StreamIndicators |
| Bidirectional | Real-time sync, interactive analysis | SyncTopology, LiveAnalysis |
Proto File References
Download the proto files to generate client stubs in any supported language.
| Proto File | Package | Description |
|---|---|---|
orbmesh/v1/mesh_service.proto | orbvpn.mesh.v1 | OrbMesh control plane -- node management, topology, metrics |
orbnet/v1/vpn_service.proto | orbvpn.vpn.v1 | VPN tunnel management -- WireGuard, VLESS, OrbConnect |
orbguard/v1/threat_service.proto | orbvpn.guard.v1 | Threat intelligence -- indicators, analysis, streaming |
orbvpn/v1/common.proto | orbvpn.v1 | Shared 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.protoDevelopment 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/StreamThreatsError Handling
gRPC uses standard status codes. OrbVPN services return additional error details in the status metadata.
| gRPC Code | Meaning | Common Cause |
|---|---|---|
OK (0) | Success | -- |
INVALID_ARGUMENT (3) | Bad request | Missing or invalid field in the request message |
NOT_FOUND (5) | Resource missing | Node, user, or indicator not found |
PERMISSION_DENIED (7) | Auth failure | Invalid or expired JWT/API key |
RESOURCE_EXHAUSTED (8) | Rate limited | Too many requests -- retry with backoff |
UNAVAILABLE (14) | Service down | Transient failure -- retry with backoff |
UNAUTHENTICATED (16) | No credentials | Missing 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.