Python SDK
Async Python SDK for Flo — native asyncio with full type annotations.
Installation
pip install flo-python
Quick Start
import asyncio
from flo import FloClient
async def main():
async with FloClient("localhost:9000") as client:
# KV
await client.kv.put("user:123", b"John Doe")
value = await client.kv.get("user:123")
print(f"Got: {value.decode()}")
# Queue
seq = await client.queue.enqueue("tasks", b'{"task": "process"}')
result = await client.queue.dequeue("tasks", 10)
for msg in result.messages:
print(msg.payload)
await client.queue.complete("tasks", result) # within the lease, or they're delivered again
# Stream
await client.stream.append("events", b'{"event": "login"}')
result = await client.stream.read("events")
for rec in result.records:
print(rec.payload)
asyncio.run(main())
KV Operations
from flo import Condition, GetOptions, PutOptions, ScanOptions, HistoryOptions
# Put returns PutResult with the new version
res = await client.kv.put("session:abc", b"data", PutOptions(ttl_ms=3_600_000))
print("committed at v", res.version)
# Get returns GetResult | None \u2014 carries both value and version
r = await client.kv.get("key")
if r is not None:
print(r.value, "@", r.version)
# Wait up to 5 s for the key to appear (wait_for=WaitFor.CHANGE waits for its next version)
r = await client.kv.get("key", GetOptions(wait_ms=5000))
# Put with CAS \u2014 use the version returned by Get/Put
r = await client.kv.get("counter")
await client.kv.put("counter", b"2", PutOptions(cas_version=r.version))
# Conditional writes
await client.kv.put("key", b"value", PutOptions(condition=Condition.IF_ABSENT))
# Delete
existed = await client.kv.delete("key") # a missing key isn't an error
# Multi-key get (single round trip, up to 256 keys, may span shards)
entries = await client.kv.mget(["user:1", "user:2", "user:3"])
for e in entries:
if e.found:
print(f"{e.key} = {e.value!r} (v{e.version})")
else:
print(f"{e.key} missing")
# Scan key names (not values), page by page
result = await client.kv.scan("user:", ScanOptions(limit=100))
print(result.names)
while result.cursor is not None:
result = await client.kv.scan("user:", ScanOptions(cursor=result.cursor))
# Version history
history = await client.kv.history("user:123", HistoryOptions(limit=10)) # version, at_ms, value
# Atomic counter
n = (await client.kv.incr("visits:home")).value # +1
n = await client.kv.incr("visits:home", KVIncrOptions(delta=10))
# TTL lifecycle and existence
await client.kv.expire("lock:resource", 60_000) # extend TTL to 60 s
await client.kv.expire("lock:resource", 0) # clear TTL
ok = await client.kv.exists("lock:resource")
# JSON paths
await client.kv.json_set("order:42", "$", b'{"items":3,"status":"new"}')
res = await client.kv.json_set("order:42", "$.status", b'"shipped"') # atomic sub-field
print("doc now at v", res.version)
status = await client.kv.json_get("order:42", "$.status") # GetResult | None
print(f"{status.value!r} @ v{status.version}")
await client.kv.json_del("order:42", "$.status")
# Per-shard transaction \u2014 atomic multi-key writes on one shard. It is pinned
# to the {tag} of the key it begins with: give every key in it the same one.
txn = await client.kv.begin("{user:42}:name")
try:
await txn.put("{user:42}:name", b"Jane")
await txn.incr("{user:42}:visits")
result = await txn.commit()
print(f"committed {result.op_count} ops at index {result.commit_index}")
except Exception:
await txn.rollback() # idempotent
raise
# Or use as an async context manager (auto-rollback on exception)
async with await client.kv.begin("{user:42}:last_seen") as txn:
await txn.put("{user:42}:last_seen", b"now")
await txn.commit()
scan, mget, json_get, json_set, json_del, and history are not supported inside a transaction and raise TxnUnsupportedOpError. Server caps: 64 ops and 256 KiB of keys and values per transaction, unless the operator sets them higher or lower (at most 256 ops and 1 MiB).
Queue Operations
from flo import EnqueueOptions, DequeueOptions
# Enqueue with a priority (lower is taken first)
seq = await client.queue.enqueue("tasks", payload,
EnqueueOptions(priority=10))
# Dequeue with long polling
result = await client.queue.dequeue("tasks", 10,
DequeueOptions(block_ms=30000))
# A dequeue leases its messages: complete each within its lease, or it is delivered again
for msg in result.messages:
process(msg.payload)
await client.queue.complete("tasks", result)
# Dead letters: up to 100, oldest first; pass after=page.last_seq for the next page
page = await client.queue.dlq_list("tasks", DlqListOptions(limit=100))
# Peek: the next ready messages, without taking them
result = await client.queue.peek("tasks", 5)
Stream Operations
from flo import StreamReadOptions, StreamAppendOptions, StreamID, StreamGroupReadOptions, StreamGroupNackOptions
# Append
result = await client.stream.append("events", b'{"event": "click"}')
# Append with headers
result = await client.stream.append("events", b'{"event": "click"}',
StreamAppendOptions(headers={"content-type": "application/json", "source": "web"}))
# Read from a specific position
result = await client.stream.read("events",
StreamReadOptions(start=StreamID(timestamp_ms=1700000000000, sequence=0), count=10))
# Read from tail (latest records)
result = await client.stream.read("events",
StreamReadOptions(tail=True, count=10))
# Blocking read (long polling)
result = await client.stream.read("events",
StreamReadOptions(tail=True, count=10, block_ms=30000))
# Access record fields
for rec in result.records:
print(rec.stream) # stream name (e.g. "events")
print(rec.payload) # raw bytes
print(rec.headers) # dict[str, str] or None
print(rec.id) # StreamID(timestamp_ms, sequence)
# Consumer groups: a read leases its records to the consumer
got = await client.stream.group_read("events", "processors", "worker-1",
StreamGroupReadOptions(count=10, block_ms=30000))
done, failed = [], []
for r in got.records:
try:
await handle(r)
done.append(r)
except Exception:
failed.append(r)
await client.stream.group_ack("events", "processors", got, done)
# Nack a failure with why (at most 1024 bytes): ready again, or dead once
# the group's attempts are spent
await client.stream.group_nack("events", "processors", got, failed,
StreamGroupNackOptions(error="payment service timed out"))
# Stopping before reaching some records? Abandon them: ready at once, no
# failure counted. Abandon never dead-letters, so never use it for a record
# that failed, or a poison record goes round for ever.
await client.stream.group_nack("events", "processors", got, unstarted,
StreamGroupNackOptions(abandon=True))
abandon can't be given with dead, delay_ms or error (ValidationError). A report to a group that doesn't exist raises NotFoundError.
StreamWorker (high-level)
The recommended way to consume streams is the StreamWorker, created from a connected client. It handles consumer group join, polling, concurrency, ack/nack, and reconnection automatically:
from flo import FloClient, StreamContext
async with FloClient("localhost:9000", namespace="myapp") as client:
worker = client.new_stream_worker(
stream="events",
group="processors",
handler=process_event,
concurrency=5,
)
async def process_event(ctx: StreamContext) -> None:
data = ctx.json()
print(f"Stream: {ctx.stream}, ID: {ctx.stream_id}")
print(f"Headers: {ctx.headers}")
await handle(data)
await worker.start()
StreamWorker Options
| Option | Type | Default | Description |
|---|---|---|---|
stream | str | required | Stream name to consume |
group | str | "" | Consumer group name |
consumer | str | auto-generated | Consumer ID within the group |
handler | Callable | required | Async function receiving StreamContext |
concurrency | int | 10 | Max concurrent handler invocations |
batch_size | int | 10 | Records per poll |
block_ms | int | 30000 | Long-poll timeout (ms) |
message_timeout | float | 300.0 | Max seconds per handler call |
StreamContext
The handler receives a StreamContext with convenience accessors:
async def process(ctx: StreamContext) -> None:
ctx.payload # raw bytes
ctx.json() # JSON-decoded payload
ctx.into(MyModel) # JSON-decoded into a class
ctx.stream_id # StreamID (timestamp_ms, sequence)
ctx.stream # stream name
ctx.headers # dict[str, str] (empty dict if no headers)
ctx.record # full StreamRecord
Records are auto-acked on handler success and auto-nacked on exception. When the worker stops, records it read but hasn't started, and any whose handler the stop cancelled, are abandoned: ready for another consumer at once, with no attempt spent. Connection errors trigger automatic reconnect.
Context Manager
async with client.new_stream_worker(
stream="events", group="processors", handler=process,
) as worker:
await worker.start()
Action & Worker Operations
from flo import ActionType, ActionRegisterOptions
# Register and invoke actions
await client.action.register("process-image", ActionType.USER,
ActionRegisterOptions(timeout_ms=60000, max_attempts=3))
result = await client.action.invoke("process-image", payload)
status = await client.action.status(result.run_id)
ActionWorker (high-level)
The recommended way to execute actions is the ActionWorker, created from a connected client. It handles registration, polling, concurrency, and heartbeats automatically:
from flo import FloClient, ActionContext
async with FloClient("localhost:9000", namespace="myapp") as client:
worker = client.new_action_worker(concurrency=5)
@worker.action("process-image")
async def process_image(ctx: ActionContext) -> bytes:
data = ctx.json()
result = await do_processing(data)
return ctx.to_bytes({"status": "done", "result": result})
await worker.start()
Features
- Native asyncio support
- Full type annotations for IDE support
- Context manager (
async with) for automatic cleanup - StreamWorker and ActionWorker for managed consumption
- Headers on stream records (read and write)
- All operations support namespace overrides
Errors
Refusals are ServerError subclasses; the ones below are raised without a retry, or once the client's retries run out.
from flo import GroupHeldFullError, LimitError, QueueFullError
try:
await client.queue.enqueue("tasks", payload)
except QueueFullError:
... # the queue's or the shard's caps: back off and send again
| Error | When |
|---|---|
QueueFullError | An enqueue found the queue, or the shard's queues and groups together, at their caps. An OverloadedError: the client retries it with backoff, since it drains as messages are completed, and raises it once its retries run out. |
GroupHeldFullError | A group read took nothing new: the group's cap counts its leased, ready and dead records, and dead ones leave only when the group is deleted or a stream trim passes them. An OverloadedError, never retried: reading again won't help. A stream worker logs it and backs off. |
LimitError | Status limit: the node is at a limit built into the server. Only too many actions, counted per shard, is returned today; it is never retried, and no setting raises it. |