Websocket api

Real-time game state updates via WebSocket connection.

Connection

Endpoint: ws://your-backend-domain:3001/ws

Protocol: WebSocket (ws:// or wss://)

Authentication: None (public read-only)

Connection Lifecycle

Connecting

const ws = new WebSocket('ws://localhost:3001/ws');

ws.onopen = () => {
  console.log('Connected to CAIVEMEN');
};

Initial State

Upon successful connection, server immediately sends initial game state:

{
  "type": "init",
  "payload": {
    "cavemen": [...],
    "food": [...],
    "disasters": [...],
    "terrain": [...],
    "environment": {...},
    "eventLog": [...],
    "recentTransactions": [...],
    "lastUpdate": 1234567890
  }
}

Disconnection

Message Types

1

Init Message

Sent: Once upon connection Purpose: Provides complete initial state

2

State Update Message

Sent: Every 200ms (5 times per second) Purpose: Incremental state updates for smooth rendering

3

Transaction Message

Sent: Immediately when transaction occurs Purpose: Alert clients to new blockchain activity

Data Types

Caveman Object

Food Object

Disaster Object

Environment Object

Event Object

Transaction Object

Client Implementation Example

React Hook

Vanilla JavaScript

Update Frequency

Message Type
Frequency
Use Case

init

Once per connection

Initial load

state_update

Every 200ms (5/sec)

Smooth rendering

transaction

On transaction

Alert user

Bandwidth Considerations

Average Message Size:

  • init: ~15KB (full state)

  • state_update: ~5KB (full state)

  • transaction: ~6KB (transaction + state)

Expected Bandwidth:

  • Steady state: ~25KB/second (5 updates × 5KB)

  • With transactions: +6KB per transaction

Total per hour:

  • Quiet: ~90MB

  • Active trading: ~120MB

Reconnection Strategy

Best Practice:

Error Handling

Common Errors:

Error
Cause
Solution

Connection refused

Backend down

Retry with backoff

Invalid JSON

Parsing error

Log and ignore message

Unexpected close

Network issue

Reconnect automatically

Error Handling Example:

Performance Tips

1

Throttle rendering

Don't render every state update if browser can't keep up.

2

Interpolate positions

Use lerp for smooth movement between updates.

3

Batch updates

Collect multiple messages before rendering.

4

Offload to Web Worker

Parse JSON in background thread to avoid blocking the main thread.

Example Interpolation:

Next Steps

  • Review REST Endpoints for historical data

  • Explore Data Schema for Firestore structure

  • Learn System Architecture