Skip to main content

Samples

Code examples for consuming real-time game data from the Data Stream CDC pipeline in multiple languages.

Quick Start

All samples are available in the /samples folder with ready-to-run examples for Go, Python, and JavaScript/Node.js.

ProtocolLatencyBest For
WebSocket~5msReal-time apps, bidirectional communication
SSE~50msSimple HTTP streaming, wide compatibility
gRPC~2msType-safe backend services, built-in filters
Authentication Required

All endpoints require authentication. See the Authentication Guide for details on obtaining API keys.


WebSocket

Full-duplex TCP connection for real-time bidirectional communication.

Authentication: WebSocket requires a short-lived token (30 seconds) obtained via REST API.

Go

// samples/websocket/go/main.go
package main

import (
"encoding/json"
"io"
"log"
"net/http"
"strings"

"github.com/gorilla/websocket"
)

const apiKey = "sk_live_xxxxx" // Your API key

func getToken() (string, error) {
req, _ := http.NewRequest("POST", "https://datastream.hypetech.games/api/auth/token", nil)
req.Header.Set("X-API-Key", apiKey)

resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()

body, _ := io.ReadAll(resp.Body)
var result map[string]string
json.Unmarshal(body, &result)
return result["token"], nil
}

func main() {
// Get authentication token
token, err := getToken()
if err != nil {
log.Fatal("Failed to get token:", err)
}

// Connect with token in Sec-WebSocket-Protocol header
header := http.Header{}
header.Set("Sec-WebSocket-Protocol", token)

conn, _, err := websocket.DefaultDialer.Dial(
"wss://datastream.hypetech.games/ws/crash", header)
if err != nil {
log.Fatal("Dial error:", err)
}
defer conn.Close()

for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("Read error:", err)
return
}
var data map[string]interface{}
json.Unmarshal(message, &data)
log.Printf("[%s] Round %v", data["game_slug"], data["round_id"])
}
}
cd samples/websocket/go && go run main.go

Python

# samples/websocket/python/main.py
import asyncio
import json
import aiohttp
import websockets

API_KEY = "sk_live_xxxxx" # Your API key

async def get_token():
async with aiohttp.ClientSession() as session:
async with session.post(
"https://datastream.hypetech.games/api/auth/token",
headers={"X-API-Key": API_KEY}
) as resp:
data = await resp.json()
return data["token"]

async def main():
# Get authentication token
token = await get_token()

# Connect with token in subprotocol
async with websockets.connect(
"wss://datastream.hypetech.games/ws/crash",
subprotocols=[token]
) as ws:
async for message in ws:
data = json.loads(message)
print(f"[{data['game_slug']}] Round {data['round_id']}")

asyncio.run(main())
cd samples/websocket/python
pip install websockets aiohttp
python main.py

JavaScript (Node.js)

// samples/websocket/javascript/index.js
import WebSocket from "ws";

const API_KEY = "sk_live_xxxxx"; // Your API key

async function getToken() {
const response = await fetch("https://datastream.hypetech.games/api/auth/token", {
method: "POST",
headers: { "X-API-Key": API_KEY }
});
const data = await response.json();
return data.token;
}

async function main() {
// Get authentication token
const token = await getToken();

// Connect with token in Sec-WebSocket-Protocol header
const ws = new WebSocket("wss://datastream.hypetech.games/ws/crash", [token]);

ws.on("message", (data) => {
const result = JSON.parse(data.toString());
console.log(`[${result.game_slug}] Round ${result.round_id}`);
});

ws.on("error", console.error);
}

main();
cd samples/websocket/javascript
npm install && npm start

Browser

const API_KEY = 'sk_live_xxxxx'; // Your API key

// Step 1: Get token
async function connect() {
const tokenRes = await fetch('/api/auth/token', {
method: 'POST',
headers: { 'X-API-Key': API_KEY }
});
const { token } = await tokenRes.json();

// Step 2: Connect with token via Sec-WebSocket-Protocol
const ws = new WebSocket('wss://datastream.hypetech.games/ws/crash', [token]);

ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(`[${data.game_slug}] Round ${data.round_id}`);
};
}

connect();

SSE (Server-Sent Events)

Simple HTTP-based streaming with automatic reconnection.

Authentication: SSE uses query parameter for authentication (EventSource API doesn't support headers).

Go

// samples/sse/go/main.go
package main

import (
"encoding/json"
"log"
"net/url"
"github.com/r3labs/sse/v2"
)

const apiKey = "sk_live_xxxxx" // Your API key

func main() {
// SSE uses query parameter for authentication
sseURL := "https://datastream.hypetech.games/sse/crash?api_key=" + url.QueryEscape(apiKey)

client := sse.NewClient(sseURL)

client.Subscribe("", func(event *sse.Event) {
if len(event.Data) == 0 {
return
}
var data map[string]interface{}
json.Unmarshal(event.Data, &data)
log.Printf("[%s] Round %v", data["game_slug"], data["round_id"])
})
}
cd samples/sse/go && go run main.go

Python

# samples/sse/python/main.py
import json
import requests
import sseclient
from urllib.parse import urlencode

API_KEY = "sk_live_xxxxx" # Your API key

# SSE uses query parameter for authentication
params = urlencode({"api_key": API_KEY})
url = f"https://datastream.hypetech.games/sse/crash?{params}"

response = requests.get(
url,
stream=True,
headers={"Accept": "text/event-stream"}
)

client = sseclient.SSEClient(response)
for event in client.events():
if event.data:
data = json.loads(event.data)
print(f"[{data['game_slug']}] Round {data['round_id']}")
cd samples/sse/python
pip install sseclient-py requests
python main.py

JavaScript (Node.js)

// samples/sse/javascript/index.js
import EventSource from "eventsource";

const API_KEY = "sk_live_xxxxx"; // Your API key

// SSE uses query parameter for authentication
const url = `https://datastream.hypetech.games/sse/crash?api_key=${encodeURIComponent(API_KEY)}`;

const eventSource = new EventSource(url);

eventSource.onmessage = (event) => {
if (!event.data) return;
const data = JSON.parse(event.data);
console.log(`[${data.game_slug}] Round ${data.round_id}`);
};

eventSource.onerror = (error) => {
console.error("SSE error:", error);
};
cd samples/sse/javascript
npm install && npm start

Browser

const API_KEY = 'sk_live_xxxxx'; // Your API key

// SSE uses query parameter for authentication
const url = `/sse/crash?api_key=${encodeURIComponent(API_KEY)}`;
const eventSource = new EventSource(url);

eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(`[${data.game_slug}] Round ${data.round_id}`);
};

eventSource.onerror = () => {
console.log('Connection lost, auto-reconnecting...');
};

Production Endpoints

ProtocolURLAuthentication
WebSocketwss://datastream.hypetech.games/ws/{game}Token via Sec-WebSocket-Protocol
SSEhttps://datastream.hypetech.games/sse/{game}Header X-API-Key or query ?api_key=
gRPCgrpc-datastream.hypetech.games:50051Metadata x-api-key
gRPC Proxyhttps://datastream.hypetech.games/api/grpc/*Header X-API-Key

Available Games

  • crash, double, dice, plinko
  • aviador, aviator-wars, foguetinho
  • motograu, motograu-v2
  • fortune-dragon, wall-street
  • free-style, freestyle-v2, pipa-brazil

Message Format

{
"round_id": 67890,
"game_slug": "crash",
"game_type": "multiplier",
"finished_at": "2026-01-18T10:00:30Z",
"extras": "{\"point\": \"2.50\"}",
"timestamp": 1737194400000
}

The timestamp field (Unix milliseconds) allows calculating end-to-end latency from database to client.

Dependencies

ProtocolGoPythonNode.js
WebSocketgithub.com/gorilla/websocketwebsockets, aiohttpws
SSEgithub.com/r3labs/sse/v2sseclient-py, requestseventsource
gRPCgoogle.golang.org/grpcgrpcio, grpcio-tools@grpc/grpc-js