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
StreamingServer-sent events with filter statementsServer streaming with filter statements and per-entity rate limits
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 (REST) · publish_asset_drone.go
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to publish a drone with onboard
// sensors as an asset entity. A simple flight model flies the drone in a slow turn, and the
// example publishes its motion and its gimbal pointing on every update.
//
// The drone's entity is in uxv/asset.go, its orientation helpers are in uxv/attitude.go, and the
// shared helpers are in common/.
package main
import (
"context"
"fmt"
"math"
"time"
"my-lattice-app/common"
"my-lattice-app/uxv"
)
// Flight model constants.
const (
tickSeconds = 1.0 // Time between updates, in seconds.
groundSpeed = 20.0 // Ground speed, in meters per second.
turnRateDegSec = 3.0 // Constant right turn, in degrees per second.
baseAltHae = 300.0 // Mean altitude above the WGS84 ellipsoid, in meters.
altAmplitude = 20.0 // Altitude oscillation amplitude, in meters.
altPeriod = 60.0 // Altitude oscillation period, in seconds.
gimbalPanAmp = 45.0 // Gimbal pan sweep, in degrees either side of the nose.
gimbalPeriod = 40.0 // Gimbal pan sweep period, in seconds.
gimbalTiltDeg = -20.0 // Gimbal tilt, in degrees. Negative looks down.
gravity = 9.81 // Gravitational acceleration, in meters per second squared.
// Set to false to derive the attitude from velocity alone.
autopilotReportsAttitude = true
)
func main() {
client := common.Connect()
// Set the creation time once, and keep it the same on every update.
createdTime := time.Now().UTC()
// Start near the origin, heading north.
position := common.LatLonAlt{Lat: 50.914, Lon: 0.792, Alt: baseAltHae}
courseDeg := 0.0
elapsed := 0.0
for {
// Turn at a constant rate, and oscillate the altitude.
elapsed += tickSeconds
courseDeg = math.Mod(courseDeg+turnRateDegSec*tickSeconds, 360)
w := 2 * math.Pi / altPeriod
climb := altAmplitude * w * math.Cos(w*elapsed)
course := courseDeg * math.Pi / 180
velocity := common.ENU{East: groundSpeed * math.Sin(course), North: groundSpeed * math.Cos(course), Up: climb}
position = common.Move(position, common.ENU{East: velocity.East * tickSeconds, North: velocity.North * tickSeconds})
position.Alt = baseAltHae + altAmplitude*math.Sin(w*elapsed)
// Heading equals course because the simulation has no wind. Pitch follows the climb
// angle, and bank balances the turn: atan(v * omega / g).
var attitude uxv.Quat
if autopilotReportsAttitude {
pitchDeg := math.Atan2(climb, groundSpeed) * 180 / math.Pi
rollDeg := math.Atan(groundSpeed*turnRateDegSec*math.Pi/180/gravity) * 180 / math.Pi
attitude = uxv.AttitudeToQuaternionENU(courseDeg, pitchDeg, rollDeg)
} else {
attitude = uxv.VelocityToQuaternionENU(velocity.East, velocity.North)
}
// The gimbal sweeps relative to the nose.
gimbalPan := gimbalPanAmp * math.Sin(2*math.Pi*elapsed/gimbalPeriod)
gimbal := uxv.GimbalToQuaternionENU(attitude, gimbalPan, gimbalTiltDeg)
batteryPercent := math.Max(87-0.01*elapsed, 0)
entity := uxv.Entity(createdTime, position, velocity, attitude, gimbal, batteryPercent)
if _, err := client.Entities.PublishEntity(context.Background(), entity); err != nil {
fmt.Printf("Error publishing entity: %v\n", err)
} else {
fmt.Printf("Publishing asset with entity ID: %s\n", uxv.EntityID)
}
time.Sleep(tickSeconds * time.Second)
}
}

For publishing patterns and best practices, see Create an asset and Create a track.

Streaming entities

Both protocols support server-side streaming for consuming entity updates, and both accept a filter statement that limits the stream to matching entities, such as a single target track.

gRPC: Filtering and rate limits

Use StreamEntityComponents when you need the most efficient stream. In addition to filters, this API accepts a per-entity rate limit for high-volume feeds, and its binary encoding uses less bandwidth.

// 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"
"io"
"log"
"os"
"sync/atomic"
"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"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
const (
// Replace with the entity ID of the track you want to monitor.
targetEntityID = "<ENTITY_ID>"
// Request a heartbeat every 5 seconds so silence is detectable.
heartbeatInterval = 5 * time.Second
// Warn if nothing arrives within three heartbeat intervals.
staleAfter = 3 * heartbeatInterval
)
// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *entitymanagerv1.Statement {
return &entitymanagerv1.Statement{
Operation: &entitymanagerv1.Statement_Predicate{
Predicate: &entitymanagerv1.Predicate{
FieldPath: "entity_id",
Value: &entitymanagerv1.Value{
Type: &entitymanagerv1.Value_StringType{
StringType: &entitymanagerv1.StringType{Value: entityID},
},
},
Comparator: entitymanagerv1.Comparator_COMPARATOR_EQUALITY,
},
},
}
}
// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
lat, lon, hae float64
velocityENU *[3]float64
}
// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *entitymanagerv1.Entity) *trackPosition {
if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic.GetLocation() != nil {
loc := geodetic.GetLocation()
pos := &trackPosition{
lat: loc.GetLatitudeDegrees(),
lon: loc.GetLongitudeDegrees(),
hae: loc.GetUniversalAltitudeHae().GetValueMeters(),
}
if v := geodetic.GetVelocityEnuMPerS(); v != nil {
pos.velocityENU = &[3]float64{v.GetX(), v.GetY(), v.GetZ()}
}
return pos
}
if loc := entity.GetLocation(); loc.GetPosition() != nil {
position := loc.GetPosition()
pos := &trackPosition{
lat: position.GetLatitudeDegrees(),
lon: position.GetLongitudeDegrees(),
hae: position.GetAltitudeHaeMeters().GetValue(),
}
if v := loc.GetVelocityEnu(); v != nil {
pos.velocityENU = &[3]float64{v.GetE(), v.GetN(), v.GetU()}
}
return pos
}
return nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
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 only the target, with all components. Don't set components_to_include,
// because listing components drops the others, which can include the position.
stream, err := client.StreamEntityComponents(ctx, &entitymanagerv1.StreamEntityComponentsRequest{
Filter: targetFilter(targetEntityID),
IncludeAllComponents: true,
HeartbeatPeriodMillis: uint32(heartbeatInterval.Milliseconds()),
})
if err != nil {
log.Fatalf("Error creating stream: %v", err)
}
// Watchdog: warn when neither entity updates nor heartbeats arrive.
var lastMessage atomic.Int64
lastMessage.Store(time.Now().UnixNano())
go func() {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
silence := time.Since(time.Unix(0, lastMessage.Load()))
if silence > staleAfter {
log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
silence.Seconds(), heartbeatInterval.Seconds())
}
}
}
}()
log.Printf("Monitoring target %s", targetEntityID)
var lastSourceTime time.Time
for {
response, err := stream.Recv()
if err == io.EOF {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Fatalf("Error receiving stream data: %v", err)
}
lastMessage.Store(time.Now().UnixNano())
if response.GetHeartbeat() != nil {
log.Printf("Heartbeat: %s", response.GetHeartbeat().GetTimestamp().AsTime().Format(time.RFC3339))
continue
}
event := response.GetEntityEvent()
eventType := event.GetEventType()
switch eventType {
case entitymanagerv1.EventType_EVENT_TYPE_CREATED,
entitymanagerv1.EventType_EVENT_TYPE_PREEXISTING,
entitymanagerv1.EventType_EVENT_TYPE_UPDATE:
entity := event.GetEntity()
pos := extractPosition(entity)
if pos == nil {
continue
}
// Ignore updates that are not newer than the last one seen.
sourceTime := entity.GetProvenance().GetSourceUpdateTime().AsTime()
if entity.GetProvenance().GetSourceUpdateTime() == nil {
sourceTime = event.GetTime().AsTime()
}
if !sourceTime.After(lastSourceTime) {
continue
}
lastSourceTime = sourceTime
line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
if v := pos.velocityENU; v != nil {
line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
}
log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
case entitymanagerv1.EventType_EVENT_TYPE_DELETED:
// The target expired, was deleted, or stopped matching the filter.
// A real interceptor would abort the engagement or request a new cue.
log.Printf("Target lost: %s", targetEntityID)
return
}
}
}

REST: Filtering over HTTP

Use StreamEntities for server-side streaming over HTTP. This API accepts the same filter statements as gRPC, which is sufficient for most integrations that need to follow specific entities.

Go (REST) · stream_target_track.go
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"sync/atomic"
"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"
)
const (
// Replace with the entity ID of the track you want to monitor.
targetEntityID = "<ENTITY_ID>"
// Request a heartbeat every 5 seconds so silence is detectable.
heartbeatInterval = 5 * time.Second
// Warn if nothing arrives within three heartbeat intervals.
staleAfter = 3 * heartbeatInterval
)
// targetFilter matches only the entity with the given ID. The filter is
// evaluated continuously: if the entity stops matching, you receive DELETED.
func targetFilter(entityID string) *Lattice.Statement {
return &Lattice.Statement{
Predicate: &Lattice.Predicate{
FieldPath: Lattice.String("entity_id"),
Value: &Lattice.Value{
StringType: &Lattice.StringType{Value: Lattice.String(entityID)},
},
Comparator: Lattice.PredicateComparatorComparatorEquality.Ptr(),
},
}
}
// trackPosition is the newest position of a track, with velocity if known.
type trackPosition struct {
lat, lon, hae float64
velocityENU *[3]float64
}
// extractPosition prefers kinematics, which is the recommended source for
// tracks, and falls back to location. It returns nil if neither has a position.
func extractPosition(entity *Lattice.Entity) *trackPosition {
if geodetic := entity.GetKinematics().GetKinematicsGeodetic(); geodetic != nil && geodetic.Location != nil {
loc := geodetic.Location
pos := &trackPosition{
lat: deref(loc.LatitudeDegrees),
lon: deref(loc.LongitudeDegrees),
hae: deref(loc.GetUniversalAltitudeHae().GetValueMeters()),
}
if v := geodetic.VelocityEnuMPerS; v != nil {
pos.velocityENU = &[3]float64{deref(v.X), deref(v.Y), deref(v.Z)}
}
return pos
}
if loc := entity.GetLocation(); loc != nil && loc.Position != nil {
pos := &trackPosition{
lat: deref(loc.Position.LatitudeDegrees),
lon: deref(loc.Position.LongitudeDegrees),
hae: deref(loc.Position.AltitudeHaeMeters),
}
if v := loc.VelocityEnu; v != nil {
pos.velocityENU = &[3]float64{deref(v.E), deref(v.N), deref(v.U)}
}
return pos
}
return nil
}
// deref returns the value of an optional field, or the zero value if unset.
func deref[T any](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}
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),
)
// Stream only the target. Omit ComponentsToInclude to receive all components,
// because listing components drops the others, which can include the position.
stream, err := latticeClient.Entities.StreamEntities(ctx, &Lattice.EntityStreamRequest{
Filter: targetFilter(targetEntityID),
HeartbeatIntervalMs: Lattice.Int(int(heartbeatInterval.Milliseconds())),
})
if err != nil {
log.Fatalf("Failed to create entity stream: %v", err)
}
defer stream.Close()
// Watchdog: warn when neither entity updates nor heartbeats arrive.
var lastMessage atomic.Int64
lastMessage.Store(time.Now().UnixNano())
go func() {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
silence := time.Since(time.Unix(0, lastMessage.Load()))
if silence > staleAfter {
log.Printf("WARNING: no message for %.1fs (expected a heartbeat every %.0fs)",
silence.Seconds(), heartbeatInterval.Seconds())
}
}
}
}()
log.Printf("Monitoring target %s", targetEntityID)
var lastSourceTime time.Time
for {
message, err := stream.Recv()
if errors.Is(err, io.EOF) {
log.Println("Stream completed successfully.")
return
}
if err != nil {
log.Fatalf("Error receiving message: %v", err)
}
lastMessage.Store(time.Now().UnixNano())
switch message.Event {
case "heartbeat":
log.Printf("Heartbeat: %s", *message.Heartbeat.Timestamp)
case "entity":
event := message.Entity
eventType := deref(event.EventType)
switch eventType {
case Lattice.EntityEventEventTypeEventTypeCreated,
Lattice.EntityEventEventTypeEventTypePreexisting,
Lattice.EntityEventEventTypeEventTypeUpdate:
entity := event.Entity
pos := extractPosition(entity)
if pos == nil {
continue
}
// Ignore updates that are not newer than the last one seen.
sourceTime := deref(entity.GetProvenance().GetSourceUpdateTime())
if sourceTime.IsZero() {
sourceTime = deref(event.Time)
}
if !sourceTime.After(lastSourceTime) {
continue
}
lastSourceTime = sourceTime
line := fmt.Sprintf("%s lat=%.6f lon=%.6f hae=%.1fm", eventType, pos.lat, pos.lon, pos.hae)
if v := pos.velocityENU; v != nil {
line += fmt.Sprintf(" vel_enu=(%.1f,%.1f,%.1f)m/s", v[0], v[1], v[2])
}
log.Printf("%s age=%.1fs", line, time.Since(sourceTime).Seconds())
case Lattice.EntityEventEventTypeEventTypeDeleted:
// The target expired, was deleted, or stopped matching the filter.
// A real interceptor would abort the engagement or request a new cue.
log.Printf("Target lost: %s", targetEntityID)
return
}
}
}
}

For more information on streaming patterns and filtering strategies, see Cue and monitor.

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