Skip to content

Agent tasks

A task is one unit of agent work that streams through Redis. The client reads it over SSE and resumes after a disconnect, a reload or on a second device. The task never depends on the connection: a disconnect does not stop it. A task can be cancelled from any process, and it can pause for the user's input and continue.

from fastapi import Depends, FastAPI, HTTPException, Request
from redis_fastapi import (
    FastAPIRedis, TaskRequest, TasksDep, TaskWriter, session_expiry,
)
from redis_fastapi.a2a import Message, Part

app = FastAPI()
FastAPIRedis(app).lifespan().streams().tasks()
access = [Depends(require_context_access)]


async def triage(task: TaskWriter, request: TaskRequest) -> None:
    first = True
    async for chunk in model.stream(request.message.text()):
        await task.artifact("answer", [Part(text=chunk)], append=not first)
        first = False
    await task.artifact("answer", [Part(text="")], append=True, last_chunk=True)


@app.post("/contexts/{context_id}/messages", dependencies=access)
async def send(context_id: str, body: Message, tasks: TasksDep) -> dict:
    result = await tasks.send(triage, body, context_id=context_id,
                              task_id=body.task_id)
    return {"taskId": result.task_id, "contextId": result.context_id}


@app.get("/contexts/{context_id}/tasks/{task_id}/events", dependencies=access)
async def events(context_id: str, task_id: str, request: Request, tasks: TasksDep):
    return await tasks.sse(task_id, context_id=context_id, request=request,
                           deadline=session_expiry(request))


@app.get("/contexts/{context_id}/tasks/{task_id}", dependencies=access)
async def get(context_id: str, task_id: str, tasks: TasksDep):
    task = await tasks.get_task(task_id, context_id=context_id,
                                include_artifacts=True)
    if task is None:
        raise HTTPException(status_code=404)
    return task


@app.post("/contexts/{context_id}/tasks/{task_id}:cancel", dependencies=access)
async def cancel(context_id: str, task_id: str, tasks: TasksDep):
    return await tasks.cancel(task_id, context_id=context_id)

require_context_access is your own access check; the SDK has none (see Access). The client sends a message, then reads the task:

const TERMINAL = new Set(["TASK_STATE_COMPLETED", "TASK_STATE_FAILED",
                          "TASK_STATE_CANCELED", "TASK_STATE_REJECTED"]);
const es = new EventSource(`/contexts/${ctx}/tasks/${task}/events`);
es.onmessage = (e) => {
  const ev = JSON.parse(e.data);
  if (ev.artifactUpdate) append(ev.artifactUpdate.artifact.parts);
  if (ev.statusUpdate) {
    const s = ev.statusUpdate.status.state;
    if (s === "TASK_STATE_INPUT_REQUIRED") askUser(ev.statusUpdate.status.message);
    if (TERMINAL.has(s)) { es.close(); showOutcome(ev.statusUpdate.status); }
  }
};

How it works

Agent tasks build on Redis Streams over SSE. A task is one Redis Stream of events plus a small status hash. send() creates both and runs your producer outside the request, in the FastAPI process. Readers are ordinary stream readers: they only read, on any process of the application.

A transaction that watches the task's status makes every status change. So a terminal state never changes, and a producer from an earlier attempt cannot change the state of the one that continued the task. An event is one plain XADD. Beside each producer the SDK runs a keepalive, which reads the status once per heartbeat and stops a producer whose task was cancelled or taken over, in any process.

Relation to A2A

The feature uses the data model of A2A v1.0 (Agent2Agent): tasks, contexts, task states, messages, parts, artifacts, and status and artifact updates. Every event is an A2A StreamResponse in A2A's JSON, so an A2A client library can parse it.

It does not implement A2A's endpoints, Agent Card or push notifications. The application keeps its own routes and its own access checks.

The Python types are Pydantic models with snake_case fields and A2A's camelCase JSON, so Message works as a request body and Task as a response. Import them from redis_fastapi.a2a; the package root holds the SDK's own names. A message and an artifact must have parts, as in A2A. A field of A2A that the models do not declare, such as a message's referenceTaskIds, is kept and written back as it came; read it from model_extra.

Terms

Term Meaning
Task One unit of agent work. The SDK generates its ID: the context ID, -, and 32 hex digits.
Context A group of tasks, such as one conversation. You pass its ID, for example a chat ID, or the SDK generates one.
Message One turn: a message_id the client chooses, a role (ROLE_USER or ROLE_AGENT) and parts.
Part One piece of content: exactly one of text, data (any JSON), url or raw (bytes), with optional media_type and filename.
Artifact An output of the task: an artifact_id, an optional name, and parts. A producer can stream it in chunks.
Producer Your async def fn(task: TaskWriter, request: TaskRequest), which does the work and writes the events.
State Live: SUBMITTED, WORKING. Interrupted: INPUT_REQUIRED, AUTH_REQUIRED. Terminal: COMPLETED, FAILED, CANCELED, REJECTED.

Every state value has the TASK_STATE_ prefix; in Python they are members of TaskState. A task goes from SUBMITTED to WORKING, may move between WORKING and an interrupted state, and ends in one terminal state.


Setup

FastAPIRedis(app).lifespan().streams().tasks()

.tasks() creates the application's one Tasks, which TasksDep returns. It enables .streams() too, and every stream setting and limit applies. The feature needs Redis 7.4 or later.


Sending a message

result = await tasks.send(triage, message, context_id="chat-42")

send() creates a task, starts the producer on it, and returns a SendResult with task_id, context_id and created. Return the task ID to the client, which then opens the events route.

  • context_id names the conversation of a new task. Without one, the SDK generates one. It never takes the context from the message, which is the client's value: a message that names a context is refused with 422 unless you pass the same one. Pass the context your access check authorized.
  • task_id continues a task that waits for input (see Pausing for input). Leave it out to start a task.
  • Retries. The client chooses the messageId before it sends. A retried send with the same messageId finds the task and starts no second producer: created is False, and the task_id is the same. This holds for the task's whole lifetime.

The task's stream begins with a task event that holds the user's message, followed by a status update to WORKING.

Context IDs and message IDs may use 1 to 128 of A-Z a-z 0-9 _ . -. A malformed ID, or a message whose own contextId or taskId disagrees with the call, raises TaskInvalidId, answered with 422.

Checks before a task runs

send() creates the task and starts its producer in one step. There is no way to create a task first and start it later. So decide where each check belongs:

  • Before send(), what needs no task. Access, a rate limit, a look at whether the user may start anything now. A failure is an ordinary HTTP error, and no task exists.
  • Inside the producer, what concerns the task. A slot only one task may hold, a budget to spend once per task. A producer runs once per task, however often the send is retried, so the check runs once too. To refuse, call reject() and return: the task ends as REJECTED with your message, and the client reads it from the task like any other end.
async def triage(task: TaskWriter, request: TaskRequest) -> None:
    if not await claim_slot(request.context_id, task.task_id):
        task.reject([Part(text="Another run is already active.")])
        return
    ...

A check before send() cannot hold a place for the task: two requests at the same instant can both pass it. Use it to answer the common case early, and make the producer's check the one that decides. The incident triage example does both.


The producer

send() runs your producer as a task the SDK owns. The TaskRequest holds task_id, context_id, the user's message and continuation, which is True when the message continues a task that waited for input.

async def triage(task: TaskWriter, request: TaskRequest) -> None:
    await task.status([Part(text="Reading the dashboards")])
    result = await query_metrics(request.message.text())
    await task.status([Part(data={"tool": "metrics", "result": result})])
    first = True
    async for chunk in model.stream(result):
        await task.artifact("answer", [Part(text=chunk)], append=not first)
        first = False
    await task.artifact("answer", [Part(text="")], append=True, last_chunk=True)
Method Writes
await artifact(artifact_id, parts, *, name, append, last_chunk) An artifact, or a chunk of one
await message(parts) A message from the agent
await status(message=None) Progress: a WORKING status update with an optional message, such as a tool call. Readers get it; get_task() does not show its message
require_input(message), require_auth(message), reject(message) Nothing yet: they choose the state the task gets when the producer returns

Each await returns the entry ID. To stream text, write a first chunk, then chunks with append=True, and mark the last with last_chunk=True. A chunk with append adds its parts to the artifact; one without it replaces them.

How the producer finishes sets the task's state:

The producer State
Returns COMPLETED
Returns after require_input() / require_auth() INPUT_REQUIRED / AUTH_REQUIRED, with your message
Returns after reject() REJECTED, with your message
Raises FAILED
Is cancelled CANCELED

A FAILED update masks the cause. It carries a generic message, "The agent failed.", and metadata.redisFastapi.code set to producer_error, whatever the exception was. The exception itself is logged, and nothing of it is sent: not its text, and not a code attribute it may have.

The SDK masks the cause on purpose. An exception can hold what a client must not see: a provider's error code such as insufficient_quota or invalid_api_key, or internal text. The update is stored in the task, so everyone who reads the task later would get it too. The SDK cannot tell which detail is safe or useful to show, so it shows none.

Telling the user why a task failed is the application's job. Catch the error in the producer, say what the user should know in your own words, and then let the task fail, or refuse it:

async def triage(task: TaskWriter, request: TaskRequest) -> None:
    try:
        ...
    except ProviderQuotaError:
        await task.message([Part(text="The assistant is unavailable right now.")])
        raise                      # the task still ends FAILED, masked

Readers get your message as an event before the FAILED update. To end the task with your message in its final state, call reject([...]) and return; the task then ends as REJECTED.

Inside the producer, a write raises:

  • TaskExpired when the task outlived task_max_lifetime.
  • ValueError for an event over task_max_event_bytes, or once the producer has written task_max_events events.
  • StreamStoreError when Redis did not confirm the write. The SDK does not retry it (see Limits and limitations).

Pausing for input

A producer that needs an answer or an approval says so and returns:

async def triage(task: TaskWriter, request: TaskRequest) -> None:
    if not request.continuation:
        task.require_input([Part(text="Which service is slow?")])
        return
    ...  # request.message holds the user's answer

The task goes to INPUT_REQUIRED with that message, and no producer runs while it waits. require_auth() does the same with AUTH_REQUIRED. The client then sends a message with the task's ID:

await tasks.send(triage, answer, task_id=task_id)

send() adds the message to the task's stream, sets the task to WORKING and starts a new producer. The SDK keeps no agent state between the two producers: keep the conversation in your agent SDK's session or checkpoint store.

A message for a task that is working or has ended raises TaskNotInterrupted (409). A messageId that another task in the context already used raises TaskMessageConflict (409).


Reading

return await tasks.sse(task_id, request=request, deadline=session_expiry(request))

tasks.sse() is a stream reader with the task's own end condition. The cursor rules, the checks before the first byte and the ways a response ends are those of streams.sse(), with TaskNotFound (404) for a missing task.

  • Each frame's data: is one A2A StreamResponse: an object with exactly one of task, message, statusUpdate or artifactUpdate. There is no event: line, as in A2A, so every frame is a message event and the client looks at which key the JSON has.
  • Each frame has an id:, which A2A lacks, so EventSource resumes exactly. A2A clients ignore it.
  • With no cursor the response replays the task from its first event. A2A starts a subscription with one Task snapshot of the current state; here the first frame is the task as it was submitted, and the frames after it bring it up to date.
  • The response ends at a terminal state. A reconnect after it gets 204, which stops EventSource for good.
  • The response stays open at an interrupted state, so the continuation arrives on the same connection. An A2A client may expect the stream to close there. A client that waits for the close would wait until the connection time limit, so act on the INPUT_REQUIRED or AUTH_REQUIRED update itself, as the quick start does.

Reading without HTTP

events() is the same read for code that is not an SSE response. It runs every check when you await it, so a WebSocket handler can refuse a request before it accepts the connection. It returns a TaskEvents, an async iterator of parsed StreamResponse objects that ends at a terminal state:

events = await tasks.events(task_id)        # raises TaskNotFound here
await websocket.accept()
async with events:
    async for event in events:
        await websocket.send_text(event.to_json())

async with closes the read at once if you leave the loop early, which frees its reader slot. To read a task to its end, a plain loop is enough:

async for event in await tasks.events(result.task_id, stop_at_interrupt=True):
    if event.artifact_update:
        ...

It takes context_id, after (an entry ID to resume from) and deadline. With stop_at_interrupt=True it also ends at the interrupt the task is in: the one with no entry after it. A replay passes every earlier interrupt, which the task has since left. It holds a reader slot from the await until it ends or is closed.


Cancelling

task = await tasks.cancel(task_id, context_id=context_id)

cancel() sets the task to CANCELED and returns it. Every reader gets the update and stops. The producer stops too: in the same process at once, in another process within one stream_heartbeat_interval. The cancel reaches the model call or tool the producer waits on.

A write checks only that the task still exists. So a producer in another process can still write for up to one heartbeat after the cancel. Those events land after the terminal state, where no reader and no get_task() looks; they use memory until the task expires.

A task in an interrupted state can be cancelled. A task that already reached a terminal state raises TaskNotCancelable (409). A closed connection never cancels a task.


Producers that stop

A process that dies takes its producers with it, and they write no last state. Each reader finds out by itself: when a SUBMITTED or WORKING task adds no entry for task_silence_timeout (a minute by default), the reader sends a last update and ends:

{"statusUpdate": {"taskId": "...", "contextId": "...",
  "status": {"state": "TASK_STATE_FAILED", "timestamp": "...",
             "message": {"messageId": "lost-<taskId>", "role": "ROLE_AGENT",
                         "taskId": "...", "contextId": "...",
                         "parts": [{"text": "The agent stopped responding."}]}},
  "metadata": {"redisFastapi": {"lost": true}}}}
  • Long tool calls. While a producer is quiet, the SDK writes a hidden ping entry for it, often enough that no reader waits out the timeout. Readers never show pings.
  • The lost update is provisional. No reader writes it to Redis, and it has no id:. A producer that was only stalled can still write a real terminal state, which get_task() and new readers then show. A client that does not close on the lost update reconnects and gets it again after another timeout.
  • A Redis outage is not silence. A reader counts only reads that succeeded.
  • An interrupted task is never lost. It has no producer by design.
  • get_task() finds out from a lease. The keepalive beside a producer renews a field in the status hash once per heartbeat, and Redis expires it after task_silence_timeout. A working task without the field has lost its producer. The producer's process sets the length, so use one task_silence_timeout in every process of the application.

Task status

task = await tasks.get_task(task_id)

get_task() returns a Task with its id, context_id and status, or None when there is no such task. By default it is one HMGET, whatever the task's length. A live task whose producer has renewed nothing for task_silence_timeout comes back FAILED with the lost marker in its metadata, as its readers report it. The status is the one of the task's last change of state: a progress update from status() is an event for readers, and get_task() does not show its message.

Two arguments also read the task's stream, which costs one pass over it:

  • include_artifacts=True adds the artifacts, with the parts of their chunks joined in order.
  • history_length adds the newest messages: None for all of them, a number for that many. The default, 0, adds none.

Reading artifacts or history costs as much as the task is long

With either argument, every call reads the task's whole stream again, parses each entry, and holds the result in memory. Nothing is cached, and a small history_length still reads everything before it cuts. The SDK sets no bound on this read.

  • Do not poll with these arguments. A client that asks every two seconds for a task of 3,000 chunks makes the server read about 45,000 entries to follow it. Poll with the defaults, which cost the same for any task, and read the content from the events.
  • Do not let a client choose them freely. A user who may call such a route can call it in a loop on a large task.
  • The size of a task has no single limit. task_max_events counts the events of one producer, so each continuation may add as many again. At the defaults one producer can write about 650 MB: 10,000 events of 64 KiB.

Lifetime and expiry

A task lives task_max_lifetime (an hour by default) from the send that created it. Waits for input count, and nothing extends it. Once the task reaches a terminal state it stays readable for task_done_ttl (two minutes by default), or until its lifetime ends if that is sooner.

A task that reaches its lifetime records no terminal state. Its keys expire: get_task() returns None, an open response closes with no event, the reconnect gets 404, and a producer's next write raises TaskExpired. Set task_max_lifetime for the longest task you expect, waits included.

A messageId is remembered for the task's whole lifetime, so it can outlive a task that ended early. A retried send then raises TaskNotFound.


Shutdown and deploys

At shutdown the SDK refuses new sends with 503, waits for sends in flight, and cancels every producer. Each writes CANCELED, and then the pool closes. Producers get five seconds for this.

A deploy has two outcomes. A graceful stop ends running tasks as CANCELED, and readers get that update when they reconnect to the new process. A process killed before its lifespan runs leaves its tasks to be reported lost after task_silence_timeout. For how open responses delay a stop, see How the response ends.


Deploying as separate services

One process can serve everything, and for a small application it should. You do not need this recipe. Without it, though, three things can happen as load grows:

  • Connection starvation. Each live reader holds one Redis connection while it waits for the next entry. Readers share the pool with the rest of the application, so enough of them leave no connection for the cache, the sessions, the rate limiter or a producer's writes.
  • Duplicated events, on Redis Cluster. redis-py's Cluster client sends a command again after a timeout or a dropped connection. For artifact(), message(), status() and your own XADD that can store one event twice, when Redis ran the first write and only its reply was lost.
  • No retries for the other features, on Redis Cluster. You can turn that retry off with REDIS_CLUSTER_ERROR_RETRY_ATTEMPTS=0, but the setting covers the whole process: the cache, the sessions and the rate limiter then lose their recovery during a failover.

The recipe avoids all three. Run the same application as three services against the same Redis, and route by path:

Service Serves Why it is separate
api Everything not listed below Keeps redis-py's retries for cache, sessions, rate limits
producers Routes that call tasks.send() or run XADD Retries off: a write whose reply is lost is not sent again
streams The SSE routes Readers get a connection pool of their own

On standalone Redis or Sentinel, redis-py does not send a command again. Two services are enough there: streams, and one for everything else.

The application needs no change. Start the quick start three times:

export REDIS_URL=redis://redis-cluster:6379
export REDIS_CLUSTER=true

# api: defaults
uvicorn main:app --port 8001

# producers: never send a write again
REDIS_CLUSTER_ERROR_RETRY_ATTEMPTS=0 uvicorn main:app --port 8002

# streams: defaults
uvicorn main:app --port 8003

Each streams process serves 64 readers by default. For more, set REDIS_STREAM_MAX_READERS on that service; its pool grows with the reader cap.

Then route by path, here with nginx:

server {
    listen 8000;

    location ~ ^/contexts/[^/]+/messages$ {
        proxy_pass http://127.0.0.1:8002;   # producers
    }

    location ~ ^/contexts/[^/]+/tasks/[^/]+/events$ {
        proxy_pass http://127.0.0.1:8003;   # streams
    }

    location / {
        proxy_pass http://127.0.0.1:8001;   # api
    }
}

No sticky routing is needed: readers, producers and cancels share only Redis. cancel() and get_task() stay in the api service, since both are safe to repeat.

Keep one rule: only the producers service may serve a route that calls tasks.send() or runs XADD on a stream. Nothing checks this at runtime. A misplaced route works, and can store an event twice after a lost reply.

What you accept:

  • Everything in the producers service loses redis-py's Cluster retry, including a session lookup in its access check. During a failover a send can answer 503. A retried send is safe: it carries the same messageId.
  • A deploy of the producers service cancels its running tasks. Deploys of the other two do not.

Access

The SDK does not decide who may use a task. Authorize before every call: neither a task ID nor a context ID is a credential.

The context ID is part of the task ID, so it travels into URLs, clients and logs. It must not be a secret.

Every call but a new send() finds the task from its ID alone. Pass context_id as well when you authorize by conversation: if it differs from the task ID's context, the SDK answers as for a task that does not exist, with no Redis call. sse(), events(), cancel() and a continuing send() raise TaskNotFound, and get_task() returns None. So a user who may read chat A cannot reach chat B's task under chat A's URL.

Pass the credential's expiry as deadline to sse(), as for any stream (see Ending a connection with the credential).


Redis permissions

A process that only serves task readers runs no write command. On top of the stream reader's commands it needs two more for sse() and events(), and one more for get_task():

+xread +xrange +xinfo|stream +type +multi +exec
+hget +exists
+hmget

A process that calls send() or cancel(), or runs producers, writes: give it full command rights on the SDK's keys. It runs no Lua script: its state changes are WATCH, MULTI and EXEC transactions.


Agent SDK recipes

Agent SDKs such as the OpenAI Agents SDK, PydanticAI, Google ADK and LangGraph run the agent loop and give you its events as an async iterator. A producer is a short loop that maps those events to writes. The example apps in examples/agent_sdks/ show one file per SDK. These SDKs often rename their events, so check an example against the version you run.

The rules are the same for every SDK:

  • A text delta is an artifact chunk. Write the first under one artifact_id, the rest with append=True, and the last with last_chunk=True.
  • A tool call or a tool result is a status update. Call status() with a Part(data=...) that holds the fields the client shows.
  • Map events, do not store them whole. An SDK event often holds the agent and its tools, and can be large. Pick the fields the client needs. Every event must fit in task_max_event_bytes, so send a large tool result as a summary.
  • A pause for a person is require_input(). When the agent waits for an approval (OpenAI Agents SDK interruptions, PydanticAI deferred tools, ADK long-running tools, a LangGraph interrupt), call require_input() and return. Resume the agent in the producer of the next message, where request.continuation is True.
  • Let errors and cancels pass. An exception from the SDK, such as a provider error, fails the task. A cancel reaches the model call or tool the SDK waits on. Do not catch asyncio.CancelledError.
  • The conversation lives elsewhere. Keep it in the SDK's own session or checkpoint store, keyed by request.context_id.

Errors and status codes

The handler .streams() registers answers each error with {"detail": ..., "code": ...}. The stream errors apply as well: 401, 409 cursor_ahead, 422 invalid_cursor and 503.

Status Cause Exception code
204 sse(): the cursor is the terminal update - -
404 No such task: unknown, expired, or another context's TaskNotFound task_not_found
409 cancel(): the task already reached a terminal state TaskNotCancelable task_not_cancelable
409 send(): the task is not waiting for input TaskNotInterrupted task_not_interrupted
409 send(): the messageId belongs to another task in the context TaskMessageConflict task_message_conflict
413 send(): the message is larger than task_max_event_bytes TaskMessageTooLarge task_message_too_large
422 A malformed ID, or a message whose IDs disagree with the call TaskInvalidId invalid_task_id
503 Redis unavailable, or the application is shutting down StreamStoreError stream_unavailable

TaskExpired is raised only inside a producer. TaskError is the base of the task exceptions, and itself a StreamError.


Limits and limitations

  • No write retry. The SDK does not repeat a failed artifact(), message() or status(), because a second write could store the event twice. Unless the producer catches the error, the task fails. Sends, interrupts, ends and cancels are retried: each applies once.
  • A write is not checked against the task's state. It lands after a cancel from another process, for up to one heartbeat, and no reader sees it. A producer whose last status change lost its reply, and which a continuation then replaced, could also write once more into the continued task before its keepalive stops it; readers would see that event.
  • Redis Cluster can store an event twice. redis-py's Cluster client sends a command again by itself, below the SDK. Set REDIS_CLUSTER_ERROR_RETRY_ATTEMPTS=0 in the process that writes; see Deploying as separate services.
  • Producers run in the FastAPI application. A producer dies with its process and does not survive a deploy. Its task cannot be handed to another process; the user sends a new message.
  • One Cluster slot per context. A context's keys share a hash tag, so all tasks of one conversation are on one node.
  • No ListTasks. The SDK keeps no index of a context's tasks. Store the task IDs you need.
  • Events per producer. One producer may write task_max_events events, each at most task_max_event_bytes. The SDK never trims a task.
  • Readers. Each sse() response and events() iterator is a stream reader, with the limits of one.

Redis keys

Every key uses the SDK's prefix setting (REDIS_PREFIX, default rf):

<prefix>:a2a:{<contextId>}:task:<taskId>          Stream   the task's events, and hidden pings
<prefix>:a2a:{<contextId>}:task:<taskId>:status   Hash     state, status (JSON), owner, alive
<prefix>:a2a:{<contextId>}:msg:<messageId>        String   the task and send that took this messageId

The stream and the status hash expire together. alive is the producer's lease: a field with a TTL of its own, present only while a producer works (see Producers that stop). The task ID begins with the context ID, so the SDK builds a task's keys from its ID alone. Events are stored as A2A JSON, unencrypted: anyone who can read the key can read them.


Settings

Every setting is an environment variable prefixed REDIS_, so task_max_lifetime is REDIS_TASK_MAX_LIFETIME. Durations are whole seconds. The stream settings apply too.

Setting Default Notes
task_max_lifetime 3600 Lifetime of a task from its creation; waits for input count, and no write extends it
task_done_ttl 120 How long a task stays readable after a terminal state; never extends the lifetime
task_max_events 10000 Most events one producer may write
task_max_event_bytes 65536 Largest event, in bytes of JSON
task_silence_timeout 60 Silence after which a reader reports a live task's producer as lost

.tasks() raises StreamConfigurationError when task_silence_timeout is less than three times stream_heartbeat_interval. The heartbeat also sets how often a producer checks for a cancel.

Metrics: see Telemetry in the streams guide.