On this page

Asynchronous Functions

Async functions separate durable acceptance from execution. Call /async-function/{function}/{path} with the application's HTTP method, query, headers and body. SlimFaas returns 202 Accepted after the queue mutation is durably committed, without waiting for a ready replica or an application result. Delivery is at least once: make handlers idempotent.

export BASE_URL=http://127.0.0.1:30020
curl -i -X POST "$BASE_URL/async-function/fibonacci1/fibonacci" \
  -H 'Content-Type: application/json' --data '{"input":10}'

For bodies larger than 1 MiB, SlimFaas commits and validates internal offload metadata before enqueueing the request that references the body. See Functions for shared visibility, dependencies, wake-up, replica bounds and configuration, and the async Guided Tour for executable examples, including failure repair and replay.

Architecture and lifecycle

flowchart LR Caller -->|Submit| API[SlimFaas API] API -->|Durable enqueue| Queue[(SlimData Raft queue)] Queue -->|Committed| API API -->|202 Accepted| Caller Queue --> Worker[Dispatch worker] Worker -->|Ready replica and capacity| Function[HTTP or WebSocket function] Function -->|Final status or deferred callback| Worker Worker -->|Complete or retry| Queue Queue -->|Terminal failure, capture enabled| DLQ[(Function DLQ)] Operator[Operator] -->|Inspect, repair, replay| DLQ DLQ -->|Atomic fresh execution| Queue
sequenceDiagram participant C as Caller participant S as SlimFaas participant D as SlimData Raft participant W as Dispatch worker participant F as Function C->>S: /async-function/name/path S->>D: Enqueue and commit D-->>S: Durable acceptance S-->>C: 202 Accepted W->>D: Reserve eligible work W->>F: Dispatch within concurrency limits alt Final response F-->>W: Completion status W->>D: Complete, schedule retry, or capture terminal failure else Deferred completion F-->>W: 202, retain execution and concurrency slot F->>S: /async-function-callback/name/elementId/success or error S->>D: Commit completion, retry, or terminal failure end Note over C,S: No later result is sent on the original caller connection

Retry and concurrency

The HTTP worker persists known final responses before clearing local tracking during a leadership transition. If persisting a queue callback fails, it retains the completion and its capacity reservation and retries the callback. Internal offload cleanup follows the committed callback. A completion from an earlier tracking generation cannot release a replacement dispatch's local slot.

SlimFaas/NumberParallelRequest limits concurrent requests for the whole function; SlimFaas/NumberParallelRequestPerPod limits each replica. Dispatch waits for readiness, dependencies and capacity. A recipient's 202 continues occupying its slot until a callback or timeout.

Configure retries through the SlimFaas/Configuration annotation:

{
  "DefaultAsync": {
    "HttpTimeout": 120,
    "TimeoutRetries": [2, 4, 8],
    "HttpStatusRetries": [500, 502, 503, 504]
  }
}

TimeoutRetries contains delays in seconds between attempts. Final 2xx except 202 completes successfully. A retryable status or timeout uses the accepted request's retry policy; nonretryable errors and exhausted attempts are terminal failures, not successes.

Committed queue mutations signal HTTP and WebSocket workers immediately. Workers:QueuesDelayMilliseconds is a fallback interval for lost signals, leadership changes and newly eligible retries, not normal polling latency. SlimData:QueueLowLatencyEnabled defaults to true; SlimData:QueueMutationMaxWaitMilliseconds defaults to 5 (range 0–225).

Internally offloaded bodies are prepared with bounded parallelism and dispatched in FIFO order. After a durably committed terminal outcome, a separate cleanup mailbox removes local artifacts and signals remote copies; convergent orphan cleanup handles unavailable replicas. Retried requests keep their artifacts. Retained DLQ payload references remain protected until their last owner is released.

Deferred completion callbacks

The caller-facing 202 means durable enqueueing. Independently, a function returning 202 enables deferred completion: SlimFaas waits for that execution's callback, not on the original caller connection.

HTTP deliveries include:

Header Meaning
SlimFaas-Element-Id Execution ID required for a callback
SlimFaas-Try-Number Zero-based attempt number
Slimfaas-Last-Try Lowercase true or false

With TimeoutRetries: [1, 2], the three possible deliveries have attempt numbers 0, 1, 2; only attempt 2 has Slimfaas-Last-Try: true. Earlier versions incorrectly exposed one-based queue attempt numbers and inverted the final-attempt flag when retries were configured. The correction also applies to WebSocket async deliveries. Stored retry history and the number of configured deliveries are unchanged.

Use the real received element ID, not a Stream message ID or an invented UUID:

POST /async-function-callback/billing/{elementId}/success
POST /async-function-callback/billing/{elementId}/error

The callback reports completion to SlimFaas; it does not return a delayed application result to the original caller. Missing callbacks time out and follow the retry/terminal-failure policy.

Official WebSocket clients expose the same async completion model: return the actual status, or return 202 and later use SendCallbackAsync(elementId, status) / send_callback(element_id, status). Use an application-owned result store or notification mechanism when callers need results after acceptance.

Dead Letter Queues

A durable Dead Letter Queue (DLQ) retains terminal failures of accepted asynchronous HTTP and WebSocket functions. Each function has one DLQ shared across SlimFaas nodes and replicas. Capture is disabled by default. Sync calls, publications, jobs, and requests rejected before durable acceptance do not enter these queues.

Enable capture

metadata:
  name: billing
  annotations:
    SlimFaas/Function: "true"
    SlimFaas/Configuration: |
      {
        "DefaultAsync": {
          "HttpTimeout": 120,
          "TimeoutRetries": [2, 4, 8],
          "HttpStatusRetries": [500, 502, 503, 504],
          "DeadLetterQueue": {
            "Enabled": true,
            "MaxAgeSeconds": 604800,
            "MaxLength": 10000
          }
        }
      }

The default retention is seven days and 10,000 entries per function. Both limits must be positive integers. Age starts at terminal failure, not initial acceptance. Expiration and oldest-first count eviction release payload references. These are count/age limits, not byte quotas; existing admission and global storage limits still apply. New entries use the current age limit; changing it does not rewrite existing expiration timestamps.

Final 2xx responses except 202 complete successfully. A 202 keeps the execution pending, including its concurrency slot, until a completion callback or timeout. Failures use the accepted request's retry policy. A nonretryable non-success response enters the DLQ immediately; exhausting retries also enters the DLQ. The stored reason distinguishes RetriesExhausted, NonRetryableResponse, DeliveryTimeout, CallbackError, CallbackTimeout, and TransportError.

POST /async-function-callback/billing/{elementId}/success
POST /async-function-callback/billing/{elementId}/error

Disabling capture or removing a function does not purge retained entries. They remain inspectable/deletable until retention ends; replay requires the same function to exist. Retained messages never run automatically, consume execution slots, keep functions awake, or contribute to executable backlog.

Visibility and dashboard defaults

{
  "SlimFaas": {
    "EnableFront": true,
    "DeadLetterQueue": {
      "DefaultVisibility": "Private",
      "EnableFront": false
    }
  }
}

Private reuses the existing trusted-caller policy and returns 404 for unauthorized callers. It protects all DLQ reads, bodies, actions, replay receipts, metrics, and live summaries/activity. Public function visibility, Data visibility, and ExposeDataMetadata do not grant DLQ access.

Setting DefaultVisibility to Public explicitly exposes original payloads and management actions, including replay and deletion. Do this only in a trusted environment or behind an independently authenticated gateway.

The two dashboard surfaces require both SlimFaas:EnableFront and SlimFaas:DeadLetterQueue:EnableFront, plus caller authorization. The specific front flag does not disable REST APIs or capture. In environment variables:

export SlimFaas__DeadLetterQueue__EnableFront=true
export SlimFaas__DeadLetterQueue__DefaultVisibility=Private

Dashboard links:

  • /#/dead-letters: searchable function catalog.
  • /#/dead-letters/billing: filtered, paginated retained messages.
  • /#/dead-letters/billing/messages/{messageId}: details and replay lineage.
  • Live Stream > Traffic: one box per function combines its asynchronous queue and DLQ, with separate queued/retained counters (including zero), function/event filters, and links from queue/function details and journal entries. Retained failures remain visible after function removal; job queues stay separate.

Combined asynchronous queue and DLQ counters in live traffic

Bodies load only after Preview body or Download body. Preview is capped at 64 KiB, marks truncation, and displays HTML/JSON as inert text. Download streams the original bytes with the original content type as an attachment. Neither opening the page nor inspecting a body wakes a function.

Illustrated example

These captures use a real three-node native-local cluster with synthetic billing requests returning HTTP 400 and an empty notifications DLQ. After fixing the application, the Requeue action creates a new execution and the Traffic journal records dead letter requeued. The HTML example has a 2.1 MiB offloaded body; its 64 KiB preview remains inert.

Function catalog with three retained billing failures and an empty notifications queue

View Example
Filtered message list Failure reason, HTTP status, attempts, retention and request sizes
Message detail and JSON preview Original request, replay/delete actions and explicit body download
Bounded HTML preview Inert text, truncation notice and full-body download
Overview function details Retained count and direct DLQ link
Traffic DLQ actor details Separate DLQ actor, retained count and management link
Replay event journal Function/event filters and the DLQ-to-function replay transition
Mobile catalog Responsive navigation and horizontally scrollable inventory

Management API

Method Route Result
GET /data/dead-letters Function catalog
GET /data/dead-letters/{function} Summary, retention and revision
GET /data/dead-letters/{function}/messages Message metadata page
GET /data/dead-letters/{function}/messages/{messageId} Original request metadata and failure
GET /data/dead-letters/{function}/messages/{messageId}/body Original body; byte ranges where seekable
POST /data/dead-letters/{function}/messages/{messageId}/requeue Durable replay receipt
DELETE /data/dead-letters/{function}/messages/{messageId} Delete retained failure
GET /data/dead-letters/-/metrics Access-controlled Prometheus metrics

Identifiers are safe path segments. Pages default to limit=100, at most 500. Pass the opaque NextCursor back as URL-encoded after. Catalogs accept a function prefix; message lists accept reason and httpStatus, applied before oldest-first pagination. Listing does not consume messages or include bodies/full request headers. Details can contain application headers and query strings and should be treated as sensitive.

curl "$SLIMFAAS/data/dead-letters?limit=100"
curl "$SLIMFAAS/data/dead-letters/billing/messages?reason=NonRetryableResponse&httpStatus=400"
curl "$SLIMFAAS/data/dead-letters/billing/messages/$MESSAGE_ID"
curl -OJ "$SLIMFAAS/data/dead-letters/billing/messages/$MESSAGE_ID/body"
curl -X POST "$SLIMFAAS/data/dead-letters/billing/messages/$MESSAGE_ID/requeue"
curl -X DELETE "$SLIMFAAS/data/dead-letters/billing/messages/$MESSAGE_ID"

Responses: 200 read, 202 durable replay, 204 deletion, 400 invalid input, 404 absent/expired/inaccessible, 409 function or required payload unavailable, 429 admission capacity, and 503 temporary cluster/storage unavailability. A blocked replay leaves the retained entry intact.

Replay and recovery guarantees

Capture, deletion, retention, and replay are committed through SlimData/Raft. Replay receipts use the generated MemoryPack serializer directly, retaining the same stored bytes without generic virtual formatter dispatch in Native AOT builds. Capture preserves the accepted request, retry history, failure time, and inline or internally offloaded payload references in the same state transition that removes it from the executable queue. Persistence failures are reported and retried; a pending completion is not deliberately dispatched again just to retry its transfer.

Replay atomically removes the retained entry and inserts a fresh execution in the same function's normal queue. It preserves method/path/query/body and application headers, generates fresh SlimFaas execution headers, resets attempts, uses current retry settings, and participates in normal backpressure, concurrency, wake-up, and autoscaling.

Concurrent/repeated replays return the same receipt for 24 hours, with DeadLetterId, OriginalElementId, ElementId, and Function. An uncertain response should be retried with that same DLQ ID. After receipt expiration it returns 404, never inserts a second copy. Old callbacks cannot complete the new element. A replay that fails again creates another DLQ entry with lineage back to the original execution.

202 means requeued, not processed successfully. Application delivery is still at-least-once; handlers must tolerate duplicate/partial side effects.

WebSocket clients

Both SDKs already send a JSON configuration string; no new wire field is needed. The runtime now validates and honors that string for retry/DLQ configuration. All clients sharing a function name must use identical configuration.

var config = new SlimFaasClient.SlimFaasClientConfig
{
    FunctionName = "billing",
    Configuration = """{"DefaultAsync":{"HttpTimeout":120,"DeadLetterQueue":{"Enabled":true}}}"""
};
import json
from slimfaas_client import SlimFaasClientConfig

config = SlimFaasClientConfig(
    function_name="billing",
    configuration=json.dumps({"DefaultAsync": {"DeadLetterQueue": {"Enabled": True}}}),
)

Return the actual completion status from an async handler. For deferred work, return 202 and send the existing explicit callback with its execution ID. An offloaded body is loaded before delivery through the existing base64 WebSocket contract; that transport still materializes the body in memory. The Python client's receive limit applies to the entire JSON/base64 envelope. Older clients inherited a 1 MiB cap, causing a 1009 disconnect for valid larger bodies. Current clients use a configurable, bounded 32 MiB envelope limit; see client limits. Prefer file references when envelope overhead or concurrent in-memory deliveries exceed the worker's budget. See client documentation and SDK examples.

Observability and upgrades

/data/dead-letters/-/metrics exposes slimfaas_dead_letters, slimfaas_dead_letter_transitions_total{function,outcome}, and node-local slimfaas_dead_letter_persistence_failures_total. Scrape through an authorized caller or authenticated gateway. These metrics deliberately do not enter the generally accessible /metrics endpoint, which would bypass DLQ privacy. Transition totals are persisted; do not sum the same replicated totals across nodes. Persistence failures are local counters.

Authorized state SSE frames contain up to 500 DLQ summaries. Activity contains only bounded transition/identity metadata, never bodies, full headers, or query strings. Committed dead_lettered, dead_letter_requeued, dead_letter_deleted, dead_letter_expired, and dead_letter_evicted events are best effort and can be sampled/missed; use snapshots/API revisions as the source of truth. The durable recent-transition window is bounded to 128 events per function, not an exhaustive audit log. Structured logs include message IDs without bodies.

This feature advertises SLDC/3. Upgrade all Raft members together: mixed SLDC/1, SLDC/2 and SLDC/3 nodes refuse mutation traffic until compatible. Existing queue snapshots, WAL commands, and producer receipts remain readable. See unified batching.

Native local exercise

For a repeatable demonstration without editing application code, follow the Guided Tour's repair exercise. The standard demo includes its sample handler and a shared, run-scoped dependency flag with a ten-minute TTL; the replay completion marker proves the fresh execution actually succeeded. No additional feature configuration is needed. Public DLQ management in the demo permits inspection, replay and deletion; keep it isolated from untrusted users.

For a manual application-fix experiment instead:

dotnet run --project src/SlimFaas -- local up -f ../../slimfaas.local.yaml

In another terminal:

export SLIMFAAS=http://127.0.0.1:30020
# Invalid JSON input is accepted by the gateway but fails in the sample handler.
curl -X POST "$SLIMFAAS/async-function/fibonacci1/fibonacci" \
  -H 'Content-Type: application/json' --data '{"Input":"not-a-number"}'
curl "$SLIMFAAS/data/dead-letters/fibonacci1/messages"

Inspect the retained body and failure in the dashboard. Fix the sample handler to accept this input (or deploy the corrected application), then requeue the same message. The payload is immutable: editing a failed message is not a repair mechanism. Replaying before fixing the handler produces a new failure, not a successful job. Delete the retained entry when it is no longer needed.

Improve this page on GitHub ↗