Build a client in another language
A working Python client for the Realtime API over HTTP, building packets, publishing, long-polling and handling errors, and what changes for WebSockets.
The JavaScript SDK speaks the Realtime API for you. In any other language you build the packets yourself. This page walks through a complete Python client that publishes and receives over HTTP, with long-polling. The same steps apply in Go, Java, Swift or Rust.
The client is in the docs repository at examples/python-client, with a test that checks its packets against the
schema without a server.
1. Generate the bindings
Packets are FlatBuffers. Generate code from the protocol schema,
protocol.fbs, with flatc, and install the runtime of the same version:
flatc --python -o gen protocol.fbs
pip install flatbuffers==25.2.10 # the version `flatc --version` printsTwo things the schema doesn't say:
- Finish every packet you send with the file identifier
RTEC. Server packets carryRTES; check it before reading one. - HTTP responses hold several server packets, each after its length as a little-endian
u32.
2. Get a token
Your backend signs it, as for any client: see Sign a token for
Python. The client asks for a new one a minute before it expires, and once more if a request is refused with
AuthExpired.
3. Publish
A Publish frame inside a client packet, sent to POST /v1/publish with the token in Authorization. Give stream
events a 128-bit idempotency key, and reuse it if you retry: a retry within 10 minutes is answered with the original
receipt, not delivered twice. See Publish.
4. Receive with long-polling
The rules a long-polling client follows:
- One poll at a time. Send the next poll when the previous one ends. Overlapping polls receive the same events twice.
- Learn each topic's id first. Replies name topics by numeric id. Poll each new topic once on its own, with
wait_ms: 0, and keep the id from itsSubAck. A refused topic is reported withtopic_id0, so it can't be matched to a name in a multi-topic poll. - Send your position every time. The server keeps nothing between polls. Send each topic's last cursor with
start: After, and, for topics that carry several event types, the lastSubAck.state_latestasstate_after. - Handle gaps. A
Gapbefore a topic'sSubAckmeans events after your cursor are gone; fetch them from your own backend. - Errors by kind. Per-topic failures are
OpErrorframes inside a200. Packet-level failures are an HTTP status with aCloseframe. RetryRateLimited,Unavailable,DrainingandTimeoutafterretry_after_ms, with backoff and jitter. Never retryAuthInvalid,Forbidden,SuspendedorAuthRevoked. PollEnd { more: true }means more events are waiting: poll again at once.
The client
"""A minimal Folkways Realtime API client over HTTP: publish, and receive with long-polling.
Standard library plus the `flatbuffers` runtime and bindings generated from protocol.fbs:
flatc --python -o gen protocol.fbs
pip install flatbuffers==<the same version as flatc>
"""
import json
import random
import struct
import time
import urllib.error
import urllib.request
import uuid
import flatbuffers
from Folkways.Protocol.V1 import (
ClientFrame, ClientPacket, Close, ContentType, Cursor, Deliver, DeliveryClass, Gap, OpError, Poll, PollEnd,
PubAck, Publish, ServerBody, ServerPacket, Snapshot, StartAt, SubAck, Subscribe, Uuid128,
)
from Folkways.Protocol.V1.ClientBody import ClientBody
CLIENT_ID, SERVER_ID = b"RTEC", b"RTES"
TYPES = {DeliveryClass.DeliveryClass.Durable: "stream", DeliveryClass.DeliveryClass.LastValue: "kv",
DeliveryClass.DeliveryClass.Ephemeral: "signal"}
class RealtimeError(Exception):
def __init__(self, code, message, retry_after_ms=0):
super().__init__(f"{code}: {message}")
self.code, self.retry_after_ms = code, retry_after_ms
# ---------------------------------------------------------------- encoding
def _packet(b, frames):
"""Finish a client packet. `frames` are (corr, body type, body offset), bodies already built."""
offsets = []
for corr, body_type, body in frames:
ClientFrame.Start(b)
ClientFrame.AddCorr(b, corr)
ClientFrame.AddBodyType(b, body_type)
ClientFrame.AddBody(b, body)
offsets.append(ClientFrame.End(b))
ClientPacket.StartFramesVector(b, len(offsets))
for offset in reversed(offsets):
b.PrependUOffsetTRelative(offset)
frames_vector = b.EndVector()
ClientPacket.Start(b)
ClientPacket.AddFrames(b, frames_vector)
b.Finish(ClientPacket.End(b), file_identifier=CLIENT_ID)
return bytes(b.Output())
def publish_packet(corr, topic, name, data, delivery=None, key=None, ttl_ms=None, idempotency_key=None):
"""One Publish frame with a JSON payload. Stream events need an idempotency key: reuse it on retries."""
b = flatbuffers.Builder(256)
topic_off, name_off = b.CreateString(topic), b.CreateString(name)
payload_off = b.CreateByteVector(json.dumps(data).encode())
key_off = b.CreateString(key) if key is not None else None
Publish.Start(b)
Publish.AddTopic(b, topic_off)
Publish.AddName(b, name_off)
Publish.AddPayload(b, payload_off)
Publish.AddContentType(b, ContentType.ContentType.Json)
if delivery is not None:
Publish.AddDelivery(b, delivery)
if key_off is not None:
Publish.AddKey(b, key_off)
if ttl_ms is not None:
Publish.AddTtlMs(b, ttl_ms)
if delivery != DeliveryClass.DeliveryClass.Ephemeral:
n = (idempotency_key or uuid.uuid4()).int
Publish.AddIdempotencyKey(b, Uuid128.CreateUuid128(b, n >> 64, n & (2**64 - 1)))
return _packet(b, [(corr, ClientBody.Publish, Publish.End(b))])
def poll_packet(corr, topics, max_events=100, wait_ms=25_000):
"""One Poll frame. `topics` are dicts: {"name", "cursor": (epoch, seq) or None, "state_after": (epoch, seq) or None}."""
b = flatbuffers.Builder(512)
names = [b.CreateString(t["name"]) for t in topics]
subs = []
for t, name in zip(topics, names):
Subscribe.Start(b)
Subscribe.AddTopic(b, name)
if t.get("cursor"):
Subscribe.AddStart(b, StartAt.StartAt.After)
Subscribe.AddCursor(b, Cursor.CreateCursor(b, *t["cursor"]))
if t.get("state_after"):
Subscribe.AddStateAfter(b, Cursor.CreateCursor(b, *t["state_after"]))
subs.append(Subscribe.End(b))
Poll.StartTopicsVector(b, len(subs))
for sub in reversed(subs):
b.PrependUOffsetTRelative(sub)
topics_vector = b.EndVector()
Poll.Start(b)
Poll.AddTopics(b, topics_vector)
Poll.AddMaxEvents(b, max_events)
Poll.AddWaitMs(b, wait_ms)
return _packet(b, [(corr, ClientBody.Poll, Poll.End(b))])
# ---------------------------------------------------------------- decoding
BODIES = {ServerBody.ServerBody.PubAck: PubAck.PubAck, ServerBody.ServerBody.OpError: OpError.OpError,
ServerBody.ServerBody.SubAck: SubAck.SubAck, ServerBody.ServerBody.Gap: Gap.Gap,
ServerBody.ServerBody.Deliver: Deliver.Deliver, ServerBody.ServerBody.Snapshot: Snapshot.Snapshot,
ServerBody.ServerBody.PollEnd: PollEnd.PollEnd, ServerBody.ServerBody.Close: Close.Close}
NAMES = {v: k for k, v in vars(ServerBody.ServerBody).items() if not k.startswith("_")}
def frames(body):
"""Yield (corr, frame name, frame) from an HTTP response: server packets, each after a little-endian u32 length."""
i = 0
while i < len(body):
(n,) = struct.unpack_from("<I", body, i)
buf = body[i + 4:i + 4 + n]
i += 4 + n
if buf[4:8] != SERVER_ID:
raise RealtimeError("BadFrame", "not a server packet")
packet = ServerPacket.ServerPacket.GetRootAs(buf, 0)
for j in range(packet.FramesLength()):
frame = packet.Frames(j)
kind = BODIES.get(frame.BodyType())
if kind is None:
continue # frames this client doesn't use, e.g. Flow
table = frame.Body()
body_obj = kind()
body_obj.Init(table.Bytes, table.Pos)
yield frame.Corr(), NAMES[frame.BodyType()], body_obj
def event_dict(e):
payload = bytes(e.Payload(k) for k in range(e.PayloadLength()))
uid = e.Uid()
return {
"topic_id": e.TopicId(), "name": (e.Name() or b"").decode(), "type": TYPES.get(e.Delivery(), "stream"),
"publisher": (e.Publisher() or b"").decode(), "key": e.Key().decode() if e.Key() else None,
"deleted": e.Tombstone(), "cursor": (e.Epoch(), e.Seq()), "version": e.Version(),
"uid": str(uuid.UUID(int=(uid.Hi() << 64) | uid.Lo())) if uid and (uid.Hi() or uid.Lo()) else None,
"data": json.loads(payload) if payload and e.ContentType() == ContentType.ContentType.Json else payload,
}
# ---------------------------------------------------------------- HTTP
class Client:
def __init__(self, url, get_token):
self.url, self.get_token = url.rstrip("/"), get_token
self.token, self.expires_at, self.corr = None, 0.0, 0
def _token(self, force=False):
# Tokens live at most 15 minutes: fetch a new one a minute before this one ends.
if force or not self.token or time.time() > self.expires_at - 60:
self.token, ttl_seconds = self.get_token()
self.expires_at = time.time() + ttl_seconds
return self.token
def _post(self, path, packet, timeout):
for attempt in range(2):
req = urllib.request.Request(self.url + path, data=packet, method="POST", headers={
"Authorization": f"Bearer {self._token(force=attempt > 0)}",
"Content-Type": "application/octet-stream"})
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
return list(frames(res.read()))
except urllib.error.HTTPError as err:
closes = [f for _, kind, f in frames(err.read()) if kind == "Close"]
code = closes[0].Code() if closes else err.code
if code == 202 and attempt == 0: # AuthExpired: try once more with a new token
continue
message = closes[0].Reason().decode() if closes and closes[0].Reason() else str(err)
raise RealtimeError(code, message, closes[0].RetryAfterMs() if closes else 0) from None
def publish(self, topic, name, data, **options):
self.corr += 1
for _, kind, f in self._post("/v1/publish", publish_packet(self.corr, topic, name, data, **options), 30):
if kind == "OpError":
raise RealtimeError(f.Code(), (f.Message() or b"").decode(), f.RetryAfterMs())
if kind == "PubAck":
return {"cursor": (f.Epoch(), f.Seq()), "duplicate": f.Duplicate()}
class Poller:
"""Long-polls a set of topics, one request at a time, and remembers where each one is."""
def __init__(self, client, names):
self.client = client
self.topics = {name: {"name": name, "cursor": None, "state_after": None, "id": None} for name in names}
def _learn(self, topic):
# A refused topic is reported with topic_id 0, so learn each topic's id on its own first.
self.client.corr += 1
for _, kind, f in self.client._post("/v1/poll", poll_packet(self.client.corr, [topic], wait_ms=0), 10):
if kind == "OpError":
raise RealtimeError(f.Code(), f"{topic['name']}: {(f.Message() or b'').decode()}")
if kind == "SubAck":
topic["id"] = f.TopicId()
def poll(self, on_event, on_gap=None):
for topic in self.topics.values():
if topic["id"] is None:
self._learn(topic)
by_id = {t["id"]: t for t in self.topics.values()}
self.client.corr += 1
replies = self.client._post("/v1/poll", poll_packet(self.client.corr, list(self.topics.values())), 35)
more = False
for _, kind, f in replies:
if kind == "OpError":
if f.TopicId() == 0: # a topic was refused, e.g. after a rule change: learn ids again
for t in self.topics.values():
t["id"] = None
raise RealtimeError(f.Code(), (f.Message() or b"").decode(), f.RetryAfterMs())
continue
topic = by_id.get(f.TopicId()) if kind != "PollEnd" else None
if kind != "PollEnd" and topic is None:
continue
if kind == "Gap" and on_gap:
on_gap(topic["name"], f.Reason())
elif kind == "SubAck" and topic and f.StateLatest():
topic["state_after"] = (f.StateLatest().Epoch(), f.StateLatest().Seq())
elif kind in ("Deliver", "Snapshot"):
for k in range(f.EventsLength()):
event = event_dict(f.Events(k))
if event["cursor"][1]:
topic["cursor"] = event["cursor"] # numbered events move the cursor
on_event(topic["name"], event)
elif kind == "PollEnd":
more = f.More()
return more
def run(self, on_event, on_gap=None):
delay = 1.0
while True:
try:
self.poll(on_event, on_gap) # waits up to 25 s; with more waiting, polls again at once
delay = 1.0
except RealtimeError as err:
if err.code in (201, 203, 204, 207): # AuthInvalid, Forbidden, Suspended, AuthRevoked: don't retry
raise
wait = max(err.retry_after_ms / 1000, delay)
time.sleep(wait * random.uniform(0.5, 1.0)) # backoff with jitter
delay = min(delay * 2, 30.0)
except (urllib.error.URLError, TimeoutError):
time.sleep(delay)
delay = min(delay * 2, 30.0)Use it
from folkways_http import Client, Poller
def get_token():
token = my_backend.issue_folkways_token() # your own token endpoint or signing code
return token, 600 # the token and its lifetime in seconds
client = Client("https://realtime.folkways.net", get_token)
client.publish("rooms/1", "message", {"text": "Hello from Python"})
def show(topic, event):
print(topic, event["publisher"], event["name"], event["data"])
Poller(client, ["rooms/1", "rooms/2"]).run(show)Over a WebSocket instead
The frames are the same; the conversation is different. See WebSocket.
- Open
wss://…/v1/wsand sendHello { token }first, within 5 seconds. Each binary message is one packet, with no length prefix. Subscribeonce per topic; events then arrive as they happen, withcorr0. Match replies to requests bycorr.- Send
Pingevery 30 seconds, andReauthwith a new token when you getTokenExpiring. - After a disconnect, reconnect with backoff and subscribe again from your saved cursors.
The client checklist lists everything a production client does.