Skip to navigation

Choose a protocol

Select between gRPC and REST for your Lattice SDK integration

The Lattice SDK supports both REST and gRPC protocols. REST offers familiar HTTP/JSON workflows with automatic authentication and broad tooling support.

RESTgRPC
InstallationPackages via PyPi, Maven, npm, source via GitHubPackages generated in Lattice Schema Registry
Language SupportPython, Typescript, Java, and GoAuto-generated bindings for 16 languages
AuthenticationEnvironment token, or built-in OAuth 2.0 token managementEnvironment token, or manual OAuth token lifecycle management
StreamingSupported with basic filteringSupported with advanced filtering
API availabilityEntities, Tasks, and ObjectsEntities and Tasks
RetriesBuilt-in retries for 5xx, 408, 409, and 429 responsesNo built-in retries, implement them in your integration
On-the-wire sizeLarger packets with JSON encodingSmaller packets with binary encoding
Browser supportBetter browser supportWeaker browser support

gRPC provides binary Protocol Buffers encoding that reduces bandwidth in constrained networks. For high-frequency scenarios, the payload difference compounds quickly. Publishing 50 drone positions at 10 Hz requires ~2 Mbps with REST and JSON, compared to ~1.3 Mbps with gRPC and Protobuf:

500 bytes × 10 updates/sec × 50 drones = 250 KB/sec = ~2 Mbps
gRPC authentication

These gRPC examples authenticate with a static environment token attached as request metadata. If you are using OAuth 2.0 client credentials instead, set up the token refresh module before running the examples on this page.

Authentication

By default, the Lattice SDK authenticates with a long-lived, static environment token that you pass directly to the client for both REST and gRPC.

If you use OAuth 2.0 client credentials instead, your authentication setup differs between protocols: REST SDKs automatically manage the OAuth token lifecycle, while gRPC requires manual token management with custom credential providers.

For complete authentication details, including environment tokens and OAuth client credentials, and code examples for both protocols, see the Authenticate guide.

Reliability and retries

Networks that carry Lattice traffic, such as tactical links, satellite relays, and congested cloud egress, drop connections, throttle traffic, and return transient errors. How much of that your integration has to handle manually depends on the protocol you choose.

REST: Built-in retries for transient errors

The Lattice REST SDKs retry automatically on HTTP 5xx, 408, 409, and 429 responses, using exponential backoff starting at 1 second with a maximum of 60 seconds and ±20% jitter. The SDK also honors Retry-After, retry-after-ms, and X-RateLimit-Reset headers returned by the server. The default is 2 retries per call, and you can override this per call with request_options={"max_retries": N}.

For REST integrations, the baseline reliability story is already in the SDK. You only need a custom retry utility if you want to retry additional error classes (for example, 404 under eventual consistency) or centralize backoff policy across every call site.

gRPC: No built-in retries

The Lattice gRPC SDKs do not retry anything automatically. Every call that returns a non-OK status surfaces the error to your code unchanged. For gRPC integrations, you must implement retry logic yourself: classify gRPC status codes as retryable or terminal, apply an exponential backoff, and honor context cancellation.

For a modular, utility-driven pattern that works for both protocols, see Retry connections.

Managing objects

The Objects API is a REST-only content delivery network (CDN) service for uploading and managing files and binary data in Lattice. This API is not available in gRPC. If your integration requires file operations alongside gRPC entity or task operations, you need to use both protocols.

For more information on managing files and binary data, see Objects overview.

Publishing entities

The choice between REST and gRPC for publishing entities depends on your update frequency and data volume.

gRPC: High-throughput streaming

Use the PublishEntities API when your integration produces high volumes of entity updates. This API creates a client-side stream that efficiently publishes batches of entities in a single connection. This approach is ideal for integrations that generate large quantities of track detections, such as passive sensors or radar systems tracking multiple targets simultaneously.

// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
ontologyv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/ontology/v1"
"github.com/google/uuid"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func main() {
ctx := context.Background()
// Get environment variables
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatalf("Missing required environment variables")
}
// Set up authentication
authCredentials := &BearerTokenAuth{
Token: environmentToken,
SandboxesToken: sandboxesToken,
}
// Create gRPC connection
opts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
grpc.WithPerRPCCredentials(authCredentials),
}
conn, err := grpc.NewClient(latticeEndpoint, opts...)
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
defer conn.Close()
client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
// Create client-side streaming connection
stream, err := client.PublishEntities(ctx)
if err != nil {
log.Fatalf("Failed to create stream: %v", err)
}
log.Println("Publishing entities via client-side streaming...")
// Send multiple entities through the stream
for i := range 100 {
entity := &entitymanagerv1.Entity{
EntityId: fmt.Sprintf("entity-%s", uuid.New().String()[:8]),
Description: "Streaming track example",
Aliases: &entitymanagerv1.Aliases{
Name: fmt.Sprintf("Track-%d", i),
},
IsLive: true,
CreatedTime: timestamppb.Now(),
ExpiryTime: timestamppb.New(time.Now().Add(10 * time.Second)),
Ontology: &entitymanagerv1.Ontology{
Template: entitymanagerv1.Template_TEMPLATE_TRACK,
PlatformType: "UNKNOWN",
},
MilView: &entitymanagerv1.MilView{
Disposition: ontologyv1.Disposition_DISPOSITION_UNKNOWN,
Environment: ontologyv1.Environment_ENVIRONMENT_UNKNOWN,
},
Location: &entitymanagerv1.Location{
Position: &entitymanagerv1.Position{
LatitudeDegrees: 33.6405 + float64(i)*0.001,
LongitudeDegrees: -117.6738 + float64(i)*0.001,
AltitudeHaeMeters: wrapperspb.Double(100.0),
},
},
Provenance: &entitymanagerv1.Provenance{
IntegrationName: "streaming_example",
DataType: "track_data",
SourceUpdateTime: timestamppb.Now(),
},
}
// Send entity through stream
if err := stream.Send(&entitymanagerv1.PublishEntitiesRequest{Entity: entity}); err != nil {
log.Fatalf("Failed to send entity: %v", err)
}
if (i+1)%10 == 0 {
log.Printf("Sent %d entities", i+1)
}
// Throttle the call
time.Sleep(300 * time.Millisecond)
}
// Close the stream and receive response
_, err = stream.CloseAndRecv()
if err != nil {
log.Fatalf("Failed to close stream: %v", err)
}
log.Println("Successfully published entities")
}

REST: Individual entity updates

Use the PublishEntity API when your integration publishes entities individually or at lower frequencies. This unary API publishes one entity per request, making it well-suited for stateful entities like assets that update their position and status periodically rather than continuously.

Go
package main
import (
"context"
"fmt"
"math"
"net/http"
"os"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// velocityToYawEnu converts an ENU velocity vector into a yaw angle, in
// radians. It uses the ENU mathematical convention where a yaw of 0 points
// East and a yaw of pi/2 points North.
func velocityToYawEnu(velocityEast, velocityNorth float64) float64 {
return math.Atan2(velocityNorth, velocityEast)
}
// yawToQuaternionEnu converts a yaw angle into the attitude_enu quaternion.
// Yaw is a rotation about the ENU Up (Z) axis, so the quaternion only has Z
// and W components. The result is already unit-normalized.
func yawToQuaternionEnu(yawRad float64) *Lattice.Quaternion {
return &Lattice.Quaternion{
X: Lattice.Float64(0.0),
Y: Lattice.Float64(0.0),
Z: Lattice.Float64(math.Sin(yawRad / 2.0)),
W: Lattice.Float64(math.Cos(yawRad / 2.0)),
}
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Generate a unique ID for the entity
entityId := uuid.New().String()
// Set a radius, in degrees, to simulate the entity moving in a circle
radiusDegrees := 0.1
count := 0.0
centerLat := 50.91402185768586
centerLon := 0.79203612077257
creationTime := time.Now().UTC()
// Continuously publish the entity
for {
latestTimestamp := time.Now().UTC()
ctx := context.Background()
// Update position
count += 0.1
t := math.Pi * count / 180.0
// Derive the ENU velocity from the circular motion, then convert it
// into a yaw angle and an attitude_enu quaternion.
lat := centerLat + (radiusDegrees * math.Cos(t))
metersPerDegreeLat := 111320.0
metersPerDegreeLon := 111320.0 * math.Cos(lat*math.Pi/180.0)
velocityEast := radiusDegrees * math.Cos(t) * metersPerDegreeLon
velocityNorth := -radiusDegrees * math.Sin(t) * metersPerDegreeLat
yawRad := velocityToYawEnu(velocityEast, velocityNorth)
// Create entity to publish
entity := Lattice.Entity{
EntityID: &entityId,
Description: Lattice.String("Friendly drone asset"),
Aliases: &Lattice.Aliases{
Name: Lattice.String("Drone 1"),
},
IsLive: Lattice.Bool(true),
CreatedTime: Lattice.Time(creationTime),
ExpiryTime: Lattice.Time(latestTimestamp.Add(1 * time.Hour)),
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("UAV"),
},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentAir.Ptr(),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(centerLat + (radiusDegrees * math.Cos(t))),
LongitudeDegrees: Lattice.Float64(centerLon + (radiusDegrees * math.Sin(t))),
AltitudeAsfMeters: Lattice.Float64(1000),
},
// Report the velocity in the ENU frame, in meters per second.
// Vertical velocity is 0 at constant altitude.
VelocityEnu: &Lattice.Enu{
E: Lattice.Float64(velocityEast),
N: Lattice.Float64(velocityNorth),
U: Lattice.Float64(0.0),
},
// Report the heading as a quaternion derived from velocity.
AttitudeEnu: yawToQuaternionEnu(yawRad),
},
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("your_integration_name"),
DataType: Lattice.String("your_data_type"),
SourceUpdateTime: Lattice.Time(latestTimestamp),
},
Health: &Lattice.Health{
ConnectionStatus: Lattice.HealthConnectionStatusConnectionStatusOnline.Ptr(),
HealthStatus: Lattice.HealthHealthStatusHealthStatusHealthy.Ptr(),
// Report the health of individual subsystems in components.
// Each component needs a stable ID, a display name, and a
// health status. Here, the drone reports its battery as healthy.
Components: []*Lattice.ComponentHealth{
{
ID: Lattice.String("battery-0"),
Name: Lattice.String("Battery"),
Health: Lattice.ComponentHealthHealthHealthStatusHealthy.Ptr(),
Messages: []*Lattice.ComponentMessage{
{
Status: Lattice.ComponentMessageStatusHealthStatusHealthy.Ptr(),
Message: Lattice.String("Battery at 87% charge."),
},
},
UpdateTime: Lattice.Time(latestTimestamp),
},
},
// Live list of active alerts for the asset. Remove entries
// when the underlying condition clears; Lattice does not
// filter stale entries automatically.
ActiveAlerts: []*Lattice.Alert{},
UpdateTime: Lattice.Time(latestTimestamp),
},
// Declare the sensors carried by the asset. Each entry requires a
// stable sensor_id, a sensor_type, and at least one field of view
// so Lattice can render the sensor cone.
Sensors: &Lattice.Sensors{
Sensors: []*Lattice.Sensor{
{
SensorID: Lattice.String("camera-1"),
SensorType: Lattice.SensorSensorTypeSensorTypeCamera.Ptr(),
OperationalState: Lattice.SensorOperationalStateOperationalStateOperational.Ptr(),
FieldsOfView: []*Lattice.FieldOfView{
{
CenterRayPose: &Lattice.EntityManagerPose{
Orientation: &Lattice.Quaternion{
X: Lattice.Float64(0.0),
Y: Lattice.Float64(0.0),
Z: Lattice.Float64(0.0),
W: Lattice.Float64(1.0),
},
},
HorizontalFov: Lattice.Float64(1.047),
VerticalFov: Lattice.Float64(0.785),
Range: Lattice.Float64(2000.0),
Mode: Lattice.FieldOfViewModeSensorModeSearch.Ptr(),
},
},
},
},
},
TaskCatalog: &Lattice.TaskCatalog{
TaskDefinitions: []*Lattice.TaskDefinition{
{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.VisualId")},
{TaskSpecificationURL: Lattice.String("type.googleapis.com/anduril.tasks.v2.Investigate")},
},
},
}
// Publish the entity
_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)
// Handle errors
if err != nil {
fmt.Printf("Error publishing entity: %v\n", err)
} else {
fmt.Println("Publishing asset")
}
// Wait before next request
time.Sleep(1 * time.Second)
}
}

For detailed guidance on entity publishing patterns and best practices, see Publish entities.

Streaming entities

Both protocols support server-side streaming for consuming entity updates, with different filtering capabilities.

gRPC: Advanced filtering

Use StreamEntityComponents when you need complex filtering logic to receive only relevant entities. This API offers more robust filtering capabilities, letting you specify filter criteria for more fine-tuned streaming.

// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main
import (
"context"
"io"
"log"
"os"
"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func main() {
ctx := context.Background()
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatalf("Missing required environment variables")
}
auth := &BearerTokenAuth{
Token: environmentToken,
SandboxesToken: sandboxesToken,
}
opts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
grpc.WithPerRPCCredentials(auth),
}
conn, err := grpc.NewClient(latticeEndpoint, opts...)
if err != nil {
log.Fatalf("Did not connect: %v", err)
}
defer conn.Close()
client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
ComponentsToInclude: []string{"aliases", "location"},
})
if err != nil {
log.Fatalf("Error creating stream: %v", err)
}
log.Println("Starting to receive stream data...")
for {
response, err := stream.Recv()
if err == io.EOF {
// End of stream
log.Println("End of stream reached.")
break
}
if err != nil {
log.Fatalf("Error receiving stream data: %v", err)
}
entity := response.GetEntityEvent().GetEntity()
if position := entity.GetLocation().GetPosition(); position != nil {
log.Printf("Entity %s at location: %f, %f",
entity.EntityId,
position.LatitudeDegrees,
position.LongitudeDegrees,
)
}
}
}

REST: Component-based filtering

Use StreamEntities for server-side streaming over HTTP with component-based filtering. This API filters entities based on the presence of specific components, which is sufficient for most integration scenarios where you need entities with particular data.

Go
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
log.Fatal("Required environment variables not set.")
}
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
latticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
// Create the entity stream.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
PreExistingOnly: Lattice.Bool(false),
// Define a list of components to control which entities are fetched.
// If set, Lattice streams only entities with the components you provide.
ComponentsToInclude: []string{"aliases", "location_uncertainty"},
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
for {
select {
case <-ctx.Done():
log.Printf("Context canceled: %v", ctx.Err())
return
default:
// Continue processing
}
message, err := stream.Recv()
// Handle stream completion
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Printf("Error receiving message: %v", err)
continue
}
// Process the event based whether it is a heartbeat or entity event.
switch message.Event {
case "heartbeat":
timestamp := *message.Heartbeat.Timestamp
log.Printf("Heartbeat: %s", timestamp)
case "entity":
log.Printf("Entity: %s", *message.Entity.Entity.Aliases.Name)
default:
log.Printf("Unknown event type: %s", message.Event)
}
}
}

For more information on streaming patterns and filtering strategies, see Watch entities.

Decision guide

Use this three-step framework to guide your protocol choice:

1

When to use gRPC

Choose gRPC when your integration prioritizes performance and bandwidth efficiency:

  • Bandwidth-constrained networks: Tactical networks, satellite links, or environments where data transmission costs matter use gRPC.
  • High-throughput scenarios: Integrations that publishing hundreds of entity updates rapidly use gRPC.
  • Specialized languages: Integrations written in Rust, C++, or other languages beyond the REST SDK use gRPC bindings.
  • Custom reliability logic: Integrations that need more control over retry classification, backoff, and error handling implement it directly in their integration, since the gRPC SDKs ship no retry layer of their own.
Scenario

An autonomous drone fleet publishes sensor data and location updates at 10 Hz per vehicle. With 50 drones, you’re sending 500 entity updates per second. gRPC’s binary encoding reduces each payload by 30-50% compared to JSON, significantly decreasing bandwidth requirements.

2

When to use REST

Choose REST when your integration prioritizes development velocity and ecosystem compatibility:

  • Web applications: Dashboards, command and control interfaces, or browser-based tools use REST
  • Low-frequency operations: Periodic polling, manual workflows, or asynchronous task creation use REST
  • Objects API access: Services that manage files and binary data in Lattice use REST to integrate with the Objects API.
  • Built-in reliability: Integrations that want sensible retry defaults for transient server errors without writing a retry layer benefit from the REST SDK’s automatic retries on 5xx, 408, 409, and 429 responses.
Scenario

A command and control web dashboard queries Lattice every 5 seconds to display current entity positions. The interface creates tasks when operators interact with the UI. REST’s simplicity accelerates development, and browser compatibility is essential.

3

When to use both

Many production systems combine both protocols to leverage their respective strengths:

  • Fleet management platforms: Hardware components use gRPC for telemetry, while web interfaces use REST for visualization.
  • Multi-component systems: Edge devices publish updates using gRPC, and cloud services consume the data using REST.
  • Objects integration: Core entity, and tasking operations use gRPC, and file management is implemented in REST.
Scenario

A robotics platform has autonomous ground vehicles publishing position and sensor data via gRPC at 5 Hz. A React web application consumes this data via REST polling at 1 Hz for operator display. Mission plans are uploaded as files through the REST Objects API, then referenced in tasks sent to the robots.

What’s next