SlimFaas Clients
The Python client bounds incoming WebSocket envelopes to 32 MiB by default,
with a four-frame buffer and backpressure. Configure positive max_message_size
and max_queue constructor options for your memory budget. JSON/base64 overhead
counts toward the envelope limit; it is separate from server HTTP body limits.
Older clients inherited a 1 MiB receive limit and closed with code 1009 before
dispatching valid larger Async bodies, including 2 MB and 2 MiB. Upgrade those
clients; see Python message limits.
Server retry defaults include 504 for expired delivery reservations and
WebSocket delivery timeouts. Explicit HttpStatusRetries lists override them;
include 504 for bounded recovery after a worker/owner disappears. Existing
queue entries retain their original policy. See function retry configuration.
Async TryNumber / try_number is zero-based. With two configured retries,
deliveries are numbered 0, 1, 2, and only the final one has
IsLastTry / is_last_try set to true. Runtimes predating the queue metadata
correction exposed one-based attempts and an inverted final-attempt flag;
upgrade the runtime to obtain the corrected values. The client wire format is
unchanged. See async delivery metadata.
For retained events, use SubscribeStreams / subscribe_streams and
OnStreamMessage / on_stream_message. See Durable Streams for
registration, deferred callbacks, visibility, and reconnect semantics.
SlimFaas clients let a process register itself as a virtual function through WebSocket instead of exposing an HTTP server.
The Python client keeps strong references to active request, Stream and event handler tasks until they finish, then releases them. Awaiting application work inside a handler therefore does not leave its task vulnerable to garbage collection.
This is useful for jobs, agents, desktop services, local workers, or any process that must receive SlimFaas requests without being deployed as a Kubernetes Deployment.
Try the independent persistent WebSocket job in the Guided Tour.
It reuses FibonacciBatch --ws-mode from the base demos, exercising sync replies,
async/event processing proofs and exact Stream ACK/history checks through the official
.NET client. --subscribe-stream Public:name is repeatable; the equivalent
SLIMFAAS_SUBSCRIBE_STREAMS environment value accepts comma-separated
subscriptions. The demonstration's proof writes use SlimFaas__BaseUrl;
SLIMFAAS_WS_URL supplies one outbound connection address; comma-separated
SLIMFAAS_WS_URLS optionally opens several identically configured clients.
One connection to any node is sufficient for sync, async, Streams and events;
the base demos deliberately use one owner. --registration-key <function-name>-ready writes a bounded-TTL
readiness proof only after all configured clients successfully register.
It is optional; ordinary WebSocket mode does not require a Data Set proof.
No client API or
wire-protocol changes are required.
Multi-node routing and failure semantics
SlimData/Raft stores registration metadata, compatible configuration and a 30-second owner lease, renewed every five seconds. Sockets and pending responses remain on their owner. Any ingress discovers the virtual function and relays sync/async requests or event fan-out directly to that owner over an authenticated internal transport. This works independently of dashboard/SSE settings. Streams retain owner-local consumption with shared Raft reservations.
The owner enforces per-client capacity. Sync bodies remain streamed with bounded
buffers; cancellation propagates to the owner. An unavailable owner returns an
explicit failure, not a blind synchronous replay. Async delivery retains the
normal retry/DLQ behavior. An ambiguous attempt's element ID stays fenced on its
connection until a late callback or disconnect; retries may use another replica.
A dispatch cancelled before acquiring the socket send lock releases its ID, since
no callback can arrive. A failed active send aborts its transport before retry;
this prevents an ambiguous frame from producing a callback for a later attempt.
Events remain best effort: 204 is acceptance, not delivery confirmation, and
partial fan-out is not automatically resent. Disconnect removes the route;
crashes expire the lease, and reconnect creates a new connection identity.
An early successful sync response stops further request-body reads while an already dispatched frame finishes within the existing 300-second delivery budget. Normal response completion must not cancel that frame or its response headers: canceling an active WebSocket send can abort the shared worker connection and interrupt unrelated deliveries. Caller cancellation and actual transport failures keep their existing cancellation and fencing behavior.
Client libraries:
- .NET SlimFaasClient README
- Python slimfaas-client README
- NuGet package: SlimFaasClient
- PyPI package: slimfaas-client
The built-in Live Stream dashboard shows synchronous WebSocket dispatch/completion and publication fan-out to connected replicas. These are server-side observation events; client registration and binary/text WebSocket protocols are unchanged.
Runtime compatibility
The .NET client targets net11.0 only and requires .NET 11. This removes the previous net8.0, net9.0 and net10.0 package assets. Applications using an older runtime must upgrade before taking this client version. Registration payloads, HTTP routes, WebSocket messages and sync streaming contracts remain compatible.
The Python client supports Python 3.10 or later. It uses websockets>=16.1.1,<17
because websockets 17 requires Python 3.11. Development dependencies retain
pygments==2.19.2 until a newer distribution passes the repository's FOSSA policy.
A worker connects to SlimFaas
The worker opens an outbound WebSocket and registers a virtual function. Callers continue to use the ordinary SlimFaas HTTP routes; SlimFaas transports requests and replies over the existing connection.
Multiple connected clients with the same function name must use identical configuration. SlimFaas routes work to connected clients; starting more external worker processes remains your responsibility. See the examples below for event subscriptions and disconnect behavior.
The existing JSON Configuration (.NET) / configuration (Python) string is
validated and applied by the runtime. Set
{"DefaultAsync":{"DeadLetterQueue":{"Enabled":true}}} to opt into durable
terminal-failure capture. Retry settings, deferred callbacks, offloaded bodies,
and replay use the normal async pipeline, with fresh execution IDs. See
Dead Letter Queues for examples and
the independent private-by-default management policy.
1. Connection Endpoint
Clients connect to SlimFaas with WebSocket:
ws://<slimfaas>:<websocket-port>/ws
By default, the dedicated WebSocket port is:
5003
The port is configured with:
{
"SlimFaas": {
"WebSocketPort": 5003
}
}
Or with the environment variable:
SlimFaas__WebSocketPort=5003
0 disables the dedicated WebSocket port.
SlimFaas only accepts /ws on the configured WebSocket port. If a request reaches /ws on another port, SlimFaas returns 404.
2. Registration Flow
After opening the WebSocket, the client sends a Register message:
{
"type": 0,
"correlationId": "<id>",
"payload": {
"functionName": "my-virtual-function",
"configuration": {
"dependsOn": [],
"subscribeEvents": [{ "name": "order-created" }],
"defaultVisibility": "Public",
"pathsStartWithVisibility": [],
"configuration": "",
"replicasStartAsSoonAsOneFunctionRetrieveARequest": false,
"numberParallelRequest": 10,
"numberParallelRequestPerPod": 10,
"defaultTrust": "Trusted"
}
}
}
SlimFaas replies with RegisterResponse:
{
"type": 1,
"correlationId": "<id>",
"payload": {
"success": true,
"error": null,
"connectionId": "<connection-id>"
}
}
If registration fails, success is false and error contains the reason.
3. Virtual Functions
Each active WebSocket connection is represented inside SlimFaas as a virtual pod.
All connections registered with the same functionName form one virtual function:
PodTypeisWebSocket.- each WebSocket connection is exposed as a ready virtual pod.
- the virtual pod name is generated from the connection id, for example
ws-1a2b3c4d. - the virtual pod IP is the WebSocket connection id.
Replicasequals the number of active connections.- the virtual function appears in the status API and in the user interface like other functions.
This means that clients can be called through the normal SlimFaas routes:
GET/POST/... /function/<functionName>/<path>
GET/POST/... /async-function/<functionName>/<path>
They can also receive publish/subscribe events when they declare subscribeEvents.
4. Registration Rules
Function Name Must Be Unique
The functionName used by a WebSocket client must not match an existing Kubernetes SlimFaas function.
SlimFaas checks current Kubernetes functions during registration. If a deployment already exists with the same name, registration is refused with an error like:
Function '<name>' is already declared as a Kubernetes deployment. WebSocket clients cannot use the same name as an existing Kubernetes function.
This prevents ambiguity between real Kubernetes pods and virtual WebSocket replicas.
Same Name Requires Same Configuration
Multiple clients may register with the same functionName. This is how you scale a virtual function horizontally.
However, all clients with the same functionName must use the exact same configuration.
SlimFaas compares:
defaultVisibilitydefaultTrustnumberParallelRequestnumberParallelRequestPerPodreplicasStartAsSoonAsOneFunctionRetrieveARequestconfigurationsubscribeEventsdependsOnpathsStartWithVisibility
If a second client connects with the same functionName but a different configuration, registration is refused with an error like:
Function '<name>' already has registered clients with a different configuration. All WebSocket clients with the same function name must share the same configuration.
When the last client for a function disconnects, SlimFaas removes the stored configuration for that virtual function.
5. Load Balancing and Parallelism
When several clients are connected with the same functionName, SlimFaas selects a client with round-robin.
The selection respects numberParallelRequestPerPod:
- each WebSocket connection is treated like one pod.
ActiveRequestsis the number of pending async callbacks plus active sync streams for that connection.- if a connection has reached
numberParallelRequestPerPod, SlimFaas skips it. - if all connections are saturated, SlimFaas has no available client and returns an error for that dispatch path.
For queued async requests, the worker also respects the global function limit:
min(numberParallelRequest, connectedClients * numberParallelRequestPerPod)
6. Async Requests
Requests sent to:
/async-function/<functionName>/<path>
are stored in the SlimFaas queue. For WebSocket virtual functions, WebSocketQueuesWorker dequeues items and sends them to a connected client using an AsyncRequest message.
The payload contains:
elementId: queue item id.method: original HTTP method.path: original path.query: original query string.headers: original headers.body: request body encoded as base64.isLastTry: whether this is the final retry attempt.tryNumber: current try number.
The client handler returns an HTTP-like status code:
2xxmeans success.5xxcan trigger retries depending on the function configuration.202means the client accepted the work and will send the final callback later.
For normal statuses, the client library sends AsyncCallback automatically. For 202, the client must call the callback API manually:
- .NET:
SendCallbackAsync(elementId, statusCode) - Python:
send_callback(element_id, status_code)
If the WebSocket request times out server-side, SlimFaas returns 504 for that queue item. If the WebSocket disconnects while callbacks are pending, SlimFaas resolves them with 503.
7. Synchronous HTTP-Over-WebSocket
The .NET client's Response.WriteAsync splits large buffers into ordered chunks
of at most 64 KiB, including the byte-array Stream overload. A single large write
therefore remains below the 256 KiB complete-frame limit of cross-node peer
relays. Cancellation stops further chunks; status, headers, body bytes and the
existing wire protocol remain unchanged.
Requests sent to:
/function/<functionName>/<path>
can be forwarded to a WebSocket client using binary streaming frames.
SlimFaas sends:
SyncRequestStart: method, path, query, and headers as JSON.SyncRequestChunk: raw request body chunks.SyncRequestEnd: end of request body.
The client sends back:
SyncResponseStart: status code and response headers as JSON.SyncResponseChunk: raw response body chunks.SyncResponseEnd: end of response body.SyncCancel: cancellation if the stream must be aborted.
Binary frame format:
[type: 1 byte][correlationId: 36 ASCII bytes][flags: 1 byte][payload length: 4 bytes big-endian][payload]
The correlationId links all frames for the same synchronous request/response stream.
When a sync handler throws or raises, both official clients report the failure for it:
- if the handler has not started the response, the client sends a
500and ends the stream; - if the status and headers are already sent, the status can no longer change, so the client sends
SyncCancel. SlimFaas then aborts the HTTP response, and the caller sees a truncated response instead of waiting for an end of stream that never comes; - if the response is already complete, nothing more is sent.
8. Publish/Subscribe Events
Clients can subscribe to SlimFaas publish/subscribe events with subscribeEvents.
When SlimFaas publishes an event to a subscribed virtual function, it sends a PublishEvent message to every active WebSocket connection for that function.
The payload contains:
eventNamemethodpathqueryheadersbodyencoded as base64
Event visibility follows the same rules as Kubernetes functions:
- if an event has its own visibility, that value is used.
- otherwise it inherits
defaultVisibility.
9. Keepalive and Disconnection
Clients may send Ping messages. SlimFaas replies with Pong using the same correlationId.
When a WebSocket disconnects:
- the connection is unregistered.
- pending async callbacks are completed with
503. - pending sync streams are cancelled.
- if it was the last connection for the function, the virtual function disappears from SlimFaas status.
Both official clients reconnect automatically. The .NET client reconnects immediately after a clean close and waits ReconnectDelay after an error; its RunForeverAsync loop returns as soon as the caller's CancellationToken is cancelled, including during that delay.
10. Official Client Libraries
.NET
- README: client/dotnet/SlimFaasClient/README.md
- Package: NuGet SlimFaasClient
- Install:
dotnet add package SlimFaasClient
Python
- README: client/python/slimfaas-client/README.md
- Package: PyPI slimfaas-client
- Install:
uv add slimfaas-client