Talo Game Services
Talo is an open-source game backend with player management, leaderboards, game saves, live config, event tracking, and multiplayer features. Available with official Godot and Unity packages.
Keep Talo in charge of your players and lobbies, and let GameFlow host the dedicated game servers they play on.
How It Works
Talo can't run your own server code, so a small GameFlow function on Deno Deploy holds your API key. Each lobby is a Talo channel. When the host starts the match, the function asks GameFlow for a server and returns the connection details once it's ready. Everyone then connects directly to the game server.
The Flow
- Players sign in to Talo.
- The host creates a lobby, a Talo channel with a join code.
- Players join with the code and ready up.
- The host calls
/startwith the region to play in. - The function checks with Talo that the caller owns the lobby, then asks GameFlow for a server.
- GameFlow responds once the server is ready, and the function saves it for the lobby.
- The host marks the lobby ready. Talo tells the other players, and each one gets the address from
/server. - Everyone connects directly to the game server and plays.
Lobby State
A Talo channel holds the lobby. Only a channel's owner can change its props, so the host keeps the lobby up to date, and every player gets each change through Talo's channel_updated signal.
| State | Where it lives | Who can read it |
|---|---|---|
| Join code | Prop code | Anyone, so players can find the lobby before joining |
| Players | Channel members | Players in the lobby |
| Ready players | Prop array ready[], as Talo alias IDs | Anyone |
| Match status | Prop gameflow.status, starting and then ready | Anyone |
| Server | The function, in Deno KV | Players in the lobby, through /server |
Players send the host a ready or unready channel message, and the host updates ready[]. With a single writer, two players readying up at once can't overwrite each other.
The Function
The function wraps the GameFlow API and exposes four endpoints. Each one takes a POST with a JSON body.
| Endpoint | Body | Who | Description |
|---|---|---|---|
/regions | {} | Anyone | Lists the regions you can start servers in. |
/start | {channelId, region} | Lobby owner | Starts a server and returns its address, host and port once it's ready. |
/server | {channelId} | Players in the lobby | Returns the lobby's server, including its state and player count. |
/stop | {channelId} | Lobby owner | Stops the lobby's server. |
Players send the same headers the Talo plugin does: X-Talo-Player, X-Talo-Alias, and X-Talo-Session if they signed in with Talo player authentication. The function passes them to Talo, which only lists a lobby's members to players in it.
Each lobby has one server at a time, and starting a new one stops the previous one. The function keeps each lobby's server in Deno KV, so players can only see or stop their own lobby's server, and your GameFlow API key never leaves the function.
:::caution Use Talo player authentication Talo only verifies who a player is when they sign in with Talo player authentication, which adds a session token to every call. With other identity services, Talo trusts the player headers, and so does the function, so anyone who knows a host's alias ID could start or stop that lobby's server. :::
:::tip IP or hostname
Each server comes with both an IP address and a hostname, so pick what suits your game. Native clients can connect straight to the IP, address, over UDP or TCP. Browser games usually need TLS, so connect them to host, such as 203-0-113-42.server.gameflow.gg, which has a valid certificate.
:::
Setting It Up
The function is two files: gameflow.ts, and a deno.json that turns on Deno KV.
- Create the app on Deno Deploy and set your keys, described in Configuration.
- Add a Deno KV database. In the Deno Deploy console, open Databases, provision a Deno KV database, and assign it to the app.
- Deploy to production.
deno deploy create --org your-org --app gameflow-talo --source local --runtime-mode dynamic --entrypoint gameflow.ts
deno deploy switch --org your-org --app gameflow-talo
deno deploy env add GAMEFLOW_API_KEY "your-api-key" --secret
deno deploy env add TALO_ACCESS_KEY "your-talo-access-key" --secret
deno deploy env add GAMEFLOW_GAME_ID "your-game-id"
deno deploy --prod
{
"tasks": {
"start": "deno run --allow-net --allow-env --env-file gameflow.ts"
},
"unstable": ["kv"]
}
View the full function, gameflow.ts
// Starts GameFlow game servers for Talo lobbies.
// Reads GAMEFLOW_API_KEY, GAMEFLOW_GAME_ID and TALO_ACCESS_KEY from the environment.
const GAMEFLOW_API_URL = 'https://api.gameflow.gg'
const TALO_API_URL = Deno.env.get('TALO_API_URL') ?? 'https://api.trytalo.com'
const GAMEFLOW_API_KEY = Deno.env.get('GAMEFLOW_API_KEY') ?? ''
const GAMEFLOW_GAME_ID = Deno.env.get('GAMEFLOW_GAME_ID') ?? ''
const TALO_ACCESS_KEY = Deno.env.get('TALO_ACCESS_KEY') ?? ''
const REQUEST_TIMEOUT_MS = 10_000
const START_TIMEOUT_MS = 310_000
const REGION_PATTERN = /^[A-Za-z0-9_-]{1,64}$/
const TALO_HEADERS = ['x-talo-player', 'x-talo-alias', 'x-talo-session', 'x-talo-include-dev-data']
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': ['content-type', ...TALO_HEADERS].join(', '),
}
const GAMEFLOW_ERRORS: Record<number, string> = {
404: 'GameFlow game or server not found.',
503: 'No game servers available, try again shortly.',
504: 'The server took too long to start.',
}
const kv = await Deno.openKv()
interface Lobby {
id: number
ownerAliasId?: number
playerAliasIds: string[]
}
interface LobbyServer {
serverName: string
region: string
}
type Input = Record<string, unknown>
class HttpError extends Error {
status: number
constructor(status: number, message: string) {
super(message)
this.status = status
}
}
async function talo(request: Request, path: string) {
const headers = new Headers({ Authorization: `Bearer ${TALO_ACCESS_KEY}` })
for (const name of TALO_HEADERS) {
const value = request.headers.get(name)
if (value) headers.set(name, value)
}
const res = await fetch(TALO_API_URL + path, {
headers,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
if (res.ok) return res.json()
const error = await res.json().catch(() => ({}))
console.error(`Talo ${path} returned ${res.status}`, error)
if (res.status === 401 && error.errorCode?.endsWith('_SESSION')) {
throw new HttpError(401, 'Your Talo session is invalid.')
}
if (res.status === 403) throw new HttpError(403, 'You are not in this lobby.')
if (res.status === 404) throw new HttpError(404, 'Lobby or player not found.')
throw new HttpError(500, 'Talo request failed.')
}
async function gameflow(method: string, path: string, body?: object, timeoutMs = REQUEST_TIMEOUT_MS) {
const res = await fetch(GAMEFLOW_API_URL + path, {
method,
headers: { 'x-api-key': GAMEFLOW_API_KEY, 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
})
if (res.ok) return res.json().catch(() => ({}))
console.error(`GameFlow ${method} ${path} returned ${res.status}: ${await res.text()}`)
const message = GAMEFLOW_ERRORS[res.status]
throw message ? new HttpError(res.status, message) : new HttpError(500, 'GameFlow request failed.')
}
async function loadLobby(request: Request, channelId: unknown): Promise<Lobby> {
if (!Number.isInteger(channelId)) throw new HttpError(400, 'A valid channelId is required.')
if (!request.headers.get('x-talo-alias')) throw new HttpError(401, 'Talo player headers are required.')
const playerAliasIds: string[] = []
for (let page = 0, isLastPage = false; !isLastPage; page++) {
const data = await talo(request, `/v1/game-channels/${channelId}/members?page=${page}`)
playerAliasIds.push(...data.members.map((member: { id: number }) => String(member.id)))
isLastPage = data.isLastPage
}
const { channel } = await talo(request, `/v1/game-channels/${channelId}`)
return { id: channelId as number, ownerAliasId: channel.owner?.id, playerAliasIds }
}
function requireOwner(request: Request, lobby: Lobby) {
if (String(lobby.ownerAliasId) !== request.headers.get('x-talo-alias')) {
throw new HttpError(403, 'Only the lobby owner can do this.')
}
}
function serverKey(lobby: Lobby) {
return ['lobby-servers', lobby.id]
}
function serverPath(server: LobbyServer) {
return `/v1/games/${GAMEFLOW_GAME_ID}/servers/${server.serverName}?region=${server.region}`
}
async function savedServer(lobby: Lobby) {
const { value } = await kv.get<LobbyServer>(serverKey(lobby))
if (!value) throw new HttpError(404, 'No server started.')
return value
}
async function stopServer(lobby: Lobby, server: LobbyServer) {
try {
await gameflow('DELETE', serverPath(server))
} catch (e) {
if (!(e instanceof HttpError && e.status === 404)) throw e
}
await kv.delete(serverKey(lobby))
}
async function regions() {
const { regions } = await gameflow('GET', '/v1/regions/available')
return { regions }
}
async function start(request: Request, { channelId, region }: Input) {
if (typeof region !== 'string' || !REGION_PATTERN.test(region)) {
throw new HttpError(400, 'A valid region is required.')
}
const lobby = await loadLobby(request, channelId)
requireOwner(request, lobby)
const previous = await kv.get<LobbyServer>(serverKey(lobby))
if (previous.value) await stopServer(lobby, previous.value)
const payload = JSON.stringify({ source: 'talo', channelId: lobby.id, players: lobby.playerAliasIds })
const { server } = await gameflow(
'POST',
`/v1/games/${GAMEFLOW_GAME_ID}/servers`,
{ region, payload },
START_TIMEOUT_MS,
)
await kv.set(serverKey(lobby), { serverName: server.name, region })
return {
serverName: server.name,
region,
address: server.address,
host: server.host,
port: server.port,
ports: server.ports,
}
}
async function lobbyServer(request: Request, { channelId }: Input) {
const lobby = await loadLobby(request, channelId)
const { serverName, region } = await savedServer(lobby)
const server = await gameflow('GET', serverPath({ serverName, region }))
return {
serverName,
region,
state: server.state,
address: server.address,
host: server.host,
port: server.port,
ports: server.ports,
playerCount: server.playerCount,
playerCapacity: server.playerCapacity,
}
}
async function stop(request: Request, { channelId }: Input) {
const lobby = await loadLobby(request, channelId)
requireOwner(request, lobby)
const server = await savedServer(lobby)
await stopServer(lobby, server)
return { stopped: server.serverName }
}
const ENDPOINTS: Record<string, (request: Request, input: Input) => Promise<object>> = {
'/regions': regions,
'/start': start,
'/server': lobbyServer,
'/stop': stop,
}
function json(body: object, status = 200) {
return Response.json(body, { status, headers: CORS_HEADERS })
}
Deno.serve(async (request) => {
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS_HEADERS })
try {
const endpoint = ENDPOINTS[new URL(request.url).pathname]
if (!endpoint) throw new HttpError(404, 'Not found.')
if (request.method !== 'POST') throw new HttpError(405, 'Use POST.')
if (!GAMEFLOW_API_KEY || !GAMEFLOW_GAME_ID || !TALO_ACCESS_KEY) {
throw new HttpError(500, 'GameFlow is not configured on this server.')
}
const input = await request.json().catch(() => null)
if (typeof input !== 'object' || input === null) throw new HttpError(400, 'Body must be a JSON object.')
return json(await endpoint(request, input))
} catch (e) {
if (e instanceof HttpError) return json({ error: e.message }, e.status)
console.error(e)
return json({ error: 'Something went wrong.' }, 500)
}
})
Every server starts with the lobby's channel ID and its players' Talo alias IDs in its launch payload, so your game server knows who to expect.
Configuration
| Key | Kind | Description |
|---|---|---|
GAMEFLOW_API_KEY | Secret | Your API key, from Settings → API. |
TALO_ACCESS_KEY | Secret | A Talo access key with only the read:gameChannels scope. Create a separate one for the function. |
GAMEFLOW_GAME_ID | Plain | The GameFlow game your servers belong to. |
TALO_API_URL | Plain | Optional. Your Talo API's URL, if you self-host Talo. |
To run the function locally, put the same keys in a .env file next to it and run deno task start.
.env holds your API keys. Keep it out of version control.
Timeouts
/start responds as soon as the server is ready. GameFlow gives a new server up to 5 minutes, and /start also checks the lobby with Talo and stops its previous server first, so give every hop a little more room than that:
| Where | Setting |
|---|---|
| Function | 310 seconds for the GameFlow call, already set in gameflow.ts |
| Game client | 360 seconds, for /start only |
| Deno Deploy | Nothing to set. It has no request time limit, but it can restart an app while a request is running |
Calling From Godot
These examples use Talo's Godot plugin and assume the player has already signed in to Talo.
The Function Client
Add gameflow_function.gd as an autoload named GameFlowFunction, and set URL to your app's address. It sends the player's Talo headers with every call. If Talo says the session expired, it refreshes it and tries once more. /start gets a longer timeout, since it waits for the server.
extends Node
const URL := "https://gameflow-talo.your-org.deno.net"
const START_TIMEOUT := 360.0
const TIMEOUT := 15.0
func call_endpoint(endpoint: String, body: Dictionary = {}, can_refresh := true) -> Dictionary:
var http := HTTPRequest.new()
http.timeout = START_TIMEOUT if endpoint == "start" else TIMEOUT
add_child(http)
if http.request(URL + "/" + endpoint, _headers(), HTTPClient.METHOD_POST, JSON.stringify(body)) != OK:
http.queue_free()
return {}
var res: Array = await http.request_completed
http.queue_free()
if res[1] == 401 and can_refresh and (await Talo.player_auth.refresh()).success:
return await call_endpoint(endpoint, body, false)
var data = JSON.parse_string(res[3].get_string_from_utf8())
if res[1] != 200 or not data is Dictionary:
push_error("GameFlow /%s failed: %s" % [endpoint, data])
return {}
return data
func _headers() -> PackedStringArray:
var headers := PackedStringArray([
"Content-Type: application/json",
"X-Talo-Player: %s" % Talo.current_player.id,
"X-Talo-Alias: %s" % Talo.current_alias.id,
])
var session := Talo.player_auth.session_manager.get_session_token()
if not session.is_empty():
headers.append("X-Talo-Session: %s" % session)
if Talo.settings.is_debug_build():
headers.append("X-Talo-Include-Dev-Data: 1")
return headers
The Lobby
The rest of the examples are parts of one lobby script. lobby is the Talo channel the player is in, and _update_lobby() saves props on it, which only the host can do.
extends Node
var lobby: TaloChannel
var _ready_ids: Array[String] = []
var _starting := false
var _joined := false
func _ready() -> void:
Talo.channels.channel_updated.connect(_on_channel_updated)
Talo.channels.message_received.connect(_on_message_received)
Talo.channels.player_left.connect(_on_player_left)
func is_host() -> bool:
return lobby.owner_alias != null and lobby.owner_alias.id == Talo.current_alias.id
func _is_lobby(channel: TaloChannel) -> bool:
return lobby != null and channel.id == lobby.id
func _update_lobby(props: Dictionary) -> void:
var options := Talo.channels.UpdateChannelOptions.new()
for key in props:
options.props[key] = props[key]
await Talo.channels.update(lobby.id, options)
Creating a Lobby
The host creates the channel with a join code. The code is a prop, so anyone can find the lobby with it before joining. auto_cleanup deletes the lobby when the host leaves, and temporary_membership drops players who go offline.
func create_lobby() -> void:
var options := Talo.channels.CreateChannelOptions.new()
options.name = "%s's lobby" % Talo.current_alias.identifier
options.auto_cleanup = true
options.temporary_membership = true
options.props = { "code": _make_code() }
var result := await Talo.channels.create(options)
if result.success:
lobby = result.channel
_ready_ids.clear()
func _make_code() -> String:
const CHARS := "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
var code := ""
for i in 6:
code += CHARS[randi() % CHARS.length()]
return code
Joining With a Code
Joining also connects straight away if the match has already started. Once in, players can list each other, since Talo only shows a lobby's members to players in it.
func join_lobby(code: String) -> void:
var options := Talo.channels.GetChannelsOptions.new()
options.prop_key = "code"
options.prop_value = code.to_upper()
var page := await Talo.channels.get_channels(options)
if page and not page.channels.is_empty():
lobby = await Talo.channels.join(page.channels[0].id)
if lobby:
_connect_if_ready()
func get_players() -> Array[TaloPlayerAlias]:
var page := await Talo.channels.get_members(lobby.id)
return page.members if page else ([] as Array[TaloPlayerAlias])
Readying Up
Players tell the host when they're ready, and the host keeps ready[] up to date, including when someone leaves.
func set_ready(is_ready: bool) -> void:
if is_host():
_set_player_ready(Talo.current_alias.id, is_ready)
else:
Talo.channels.send_message(lobby.id, "ready" if is_ready else "unready")
func is_player_ready(alias_id: int) -> bool:
return lobby.get_prop_array("ready").has(str(alias_id))
func _on_message_received(channel: TaloChannel, player_alias: TaloPlayerAlias, message: String) -> void:
if _is_lobby(channel) and is_host() and message in ["ready", "unready"]:
_set_player_ready(player_alias.id, message == "ready")
func _on_player_left(channel: TaloChannel, player_alias: TaloPlayerAlias, _reason) -> void:
if _is_lobby(channel) and is_host():
_set_player_ready(player_alias.id, false)
func _set_player_ready(alias_id: int, is_ready: bool) -> void:
_ready_ids.erase(str(alias_id))
if is_ready:
_ready_ids.append(str(alias_id))
_update_lobby({ "ready[]": _ready_ids.duplicate() })
Starting the Match
The host marks the lobby as starting, calls /start, and marks it ready once the server is up. A second press while a start is running does nothing. connect_to_game_server() is your game's own networking code.
func start_match(region: String) -> void:
if _starting:
return
_starting = true
await _update_lobby({ "gameflow.status": "starting" })
var server := await GameFlowFunction.call_endpoint("start", { "channelId": lobby.id, "region": region })
_starting = false
_update_lobby({ "gameflow.status": "ready" if server else null })
if server:
connect_to_game_server(server.host, int(server.port))
Connecting
Everyone else connects when the lobby turns ready, after getting the address from /server. If that call fails, the next lobby update tries again.
func _on_channel_updated(channel: TaloChannel, _changed_properties: Array[String]) -> void:
if _is_lobby(channel):
lobby = channel
_connect_if_ready()
func _connect_if_ready() -> void:
if lobby.get_prop("gameflow.status") != "ready":
_joined = false
return
if is_host() or _joined:
return
_joined = true
var server := await GameFlowFunction.call_endpoint("server", { "channelId": lobby.id })
if server.get("state") == "Ready":
connect_to_game_server(server.host, int(server.port))
else:
_joined = false
When the match ends, let your game server shut itself down once it's empty, or have the host stop it:
func stop_match() -> void:
var stopped := await GameFlowFunction.call_endpoint("stop", { "channelId": lobby.id })
if stopped:
_update_lobby({ "gameflow.status": null })
Next Steps
- Regions: choose where your servers run.
- Launch Payload: read the lobby's players on your game server.
- Talo Channels: everything else channels can do.
- API Reference: explore every GameFlow endpoint.