Skip to content

Redis and Valkey streams for Python

Decorate a function, steer every worker.

RillKit consumes Redis and Valkey streams for you: consumer groups, retries with backoff, a dead-letter queue and a clean shutdown, around a function you write. Turn on the optional control plane and you can watch, pause, scale and replay every worker from one dashboard, and see where a message spent its time at every step it crossed.

pip install rillkit

Python 3.9+, TypeScript next Redis or Valkey, one server or a cluster Apache 2.0 Source on GitHub

Two services publish messages into the stream "orders". Three workers in the group "workers" take them; each message is acked, retried after a backoff, or moved to the dead-letter stream orders-dlq. Above the workers, the optional control plane receives their telemetry and sends them directives. RillKitmessages handled1,284 /sordersrunningpaymentspausedemailsrunningpausedrainscalerillkit-server + dashboardoptionalpublish()publish()stream: ordersgroup: workersackorders-dlqretry, after a backofftelemetry ↑ directives ↓

Simple by default

Two files and a stream name, no loop.

The publisher and the worker agree on "orders" and nothing else. No schema to register, no polling loop, no ack bookkeeping.

  1. Install itpip install rillkitPoint RILLKIT_URL at Redis or Valkey: one server or a cluster.
  2. Decorate a function@broker.subscribe(Stream(...))Name a stream and a group. Your function gets each message as a dict or a Pydantic model.
  3. Run itbroker.run()Groups, retries, the DLQ, heartbeats and a clean shutdown on Ctrl-C come with it.
publish.pypython
from rillkit import Broker

broker = Broker.from_env()  # reads RILLKIT_URL

broker.publish("orders", {"id": 1, "total": 42.5})
worker.pypython
from rillkit import AckPolicy, Broker, Message, Stream

broker = Broker.from_env()  # reads RILLKIT_URL

@broker.subscribe(
    Stream("orders", group="workers"),
    ack_policy=AckPolicy.NACK_ON_ERROR,
    max_retries=3,
)
def handle(order: dict, msg: Message):
    if order["total"] <= 0:
        msg.reject("bad total")  # straight to the DLQ
        return
    if not charge(order):
        msg.nack()  # try again after a backoff

broker.run()

The control plane · optional

Watch and steer every worker, from one place.

Set RILLKIT_CONTROL=relay and each worker reports to rillkit-server. Its dashboard shows every stream, worker and message, traces each message across streams, and lets you pause, scale and replay them. No code changes, and the library works the same without it.

The dashboard's overview: nodes online, active workers, messages in flight, total lag and ack rate; controls to pause, resume, drain or put every worker in maintenance; and the throughput section.

Workers dial out

Nothing to open, nothing to install.

Each worker opens one outbound WebSocket to the server. Telemetry goes up every few seconds; directives come back down. The server does not touch your Redis or Valkey.

  • No inbound ports on your workers, no agent beside them.
  • Keeps consuming if the server goes away, under the last state it was given.
  • One setting: RILLKIT_CONTROL=relay, a URL and an API key.
Redis / Valkeyyour network: no inbound portrillkit-serveroutbound WebSocket

Autoscale on load

More lanes when the work demands it.

Give a stream a minimum, a maximum and a target lag per worker. The autoscaler follows the arrival rate and the backlog, adds lanes when work builds and removes them when the rate falls — not just when lag hits zero.

  • Cooldowns stop it changing its mind every few seconds.
  • Safe failover: a replacement leader seeds the rate from the last samples.
  • Every decision is a directive you can read in Activity.
autoscalerstream: orders, lag risinglanes per node: 1 → 4

Messages, as they arrive

See what is in the stream right now.

Newest first, as of a moment you choose or live as messages land, each with its status: waiting, pending with its try number, or acked. Open one in place for its payload, its trace id, its logs, and View trace: every stream the trace crossed, with queue wait against handler time.

A stream's Messages tab with Live on: each message row shows its time, id, status, consumer, size and payload preview; a row is expanded in place.

Find the bottleneck

A trace, end to end.

Queue wait against handler time for every stream, and one trace across every stream a message crossed — including retries — on one time ruler. The slow step is obvious without opening a tracing stack.

A trace waterfall: the end-to-end duration at the top, a time ruler, then each handler attempt offset by its start, with stream, worker, node, queue wait and handler time.

Fix and replay the DLQ

Edit the payload, then send it back.

Page through dead letters with the reason each one failed and the logs of every attempt. Replay one, a selection or all of them, delete them, or correct a payload that could never succeed and replay just that message.

A dead-lettered message expanded under its row: the error, the original message id, the deliveries, and a JSON editor to change the payload before replaying it.
  • Pause, drain, resume

    One stream, one node or the whole fleet. Paused workers finish the message in hand; drained ones also let go of their consumers.

  • Applied exactly once

    Every change is a directive with an id. Any worker applies it once, answers, and it is listed in Activity with who sent it.

  • Throughput and trends

    Messages handled, success rate, data rate and DLQ size, with the change against the previous window: green when better, red when worse.

  • Traces and wait/work

    Queue wait against handler time per stream, and one trace across every stream a message crossed, so the slow step is obvious. Traces are opt-in metadata, kept for an hour.

  • Logs per message

    What a handler logged for one message, attempt by attempt, with its exception and W3C trace id. Opt in with RILLKIT_CAPTURE_LOGS.

  • Payloads stay put

    The server stores neither payloads, logs nor trace records. It asks a worker when you open a message or a trace, and only if that worker allows it.

  • Lanes you can change

    Raise or lower a stream’s worker lanes per node from the dashboard; workers apply it without a restart, and the autoscaler can do it for you.

  • Several replicas

    Run as many servers as you like on one Postgres. Directives reach a worker through whichever replica holds its connection.

  • Prometheus metrics

    GET /api/metrics exports replica, tenant, node, lane, in-flight, lag, pending and ack-rate gauges for your existing scrape.

See it in one command

One download starts Postgres, Valkey, rillkit-server with its dashboard, two demo workers and a producer whose load rises and falls, so lag builds, the autoscaler reacts and failures land in the DLQ. A flow service sends one traced order through two streams every two minutes. The images are published: no clone, no build.

The SDKs are Apache 2.0. rillkit-server and the dashboard are FSL-1.1-ALv2: free to self-host for your own organization, and Apache 2.0 two years after each release.

terminal
$ curl -fsSLO https://raw.githubusercontent.com/\
    NimzyMaina/RillKit/main/deploy/demo.yaml
$ docker compose -f demo.yaml up -d

# open http://localhost:8080
# admin token: rillkit-local-admin-token

Where a message ends up

It goes from publish to the handler, then takes one of three exits. There is no fourth one where it quietly disappears.

middleware wraps this partPublishbroker.publish()StreamordersGroupworkersHandleryour functionAckdoneDLQorders-dlqRetryafter backoffredelivered after backoffPublishbroker.publish()StreamordersGroupworkersHandleryour functionAckdoneDLQorders-dlqRetrybackoff
  • AckThe handler returned. The entry is acked and leaves the pending list.
  • RetryThe handler raised, or called nack(). It is delivered again after a growing backoff, up to max_retries.
  • Dead letterRetries ran out, or you called reject(). The entry moves to the DLQ with the error, original id and delivery count.

The loop you would have written

Most teams start with xreadgroup in a while True. It works until the first exception. The migration example runs both versions side by side.

consumer_raw.pypython
import json

import redis

r = redis.Redis.from_url("redis://localhost:6379/0", decode_responses=True)
try:
    r.xgroup_create("orders", "workers", id="0", mkstream=True)
except redis.ResponseError as e:
    if "BUSYGROUP" not in str(e):
        raise

while True:
    for _, entries in r.xreadgroup("workers", "web1", {"orders": ">"}, count=10, block=5000) or []:
        for entry_id, fields in entries:
            try:
                charge(json.loads(fields["data"]))
                r.xack("orders", "workers", entry_id)
            except Exception as e:
                print("failed:", e)  # and then?
worker.pypython
from rillkit import Broker, Stream

broker = Broker.from_env()

@broker.subscribe(Stream("orders", group="workers"))
def handle(order: dict):
    charge(order)

broker.run()
  • Entries stuck with a crashed worker are never claimed again.
  • A handler that keeps failing keeps failing. There is no retry limit and no backoff.
  • Nothing goes to a dead-letter stream, so bad messages pile up in the pending list.
  • Ctrl-C drops whatever was in flight.

What happens when a handler fails

  • Consumer groups

    The group is created for you and every worker gets its own consumer name. Entries left with a crashed worker are claimed back once they have sat idle long enough.

  • Retries with backoff

    A failing message comes back after an exponential backoff, up to max_retries. The default is 3, so a handler runs at most four times for one message.

  • nack or reject

    msg.nack() asks for another attempt. msg.reject("reason") says this one can never work and skips the remaining retries.

  • Dead-letter stream

    Entries that run out of retries, or are rejected, move to <stream>-dlq with the error, original id, group and delivery count. broker.replay_dlq() puts them back.

Ack policies

Choose when a message counts as done. Set it per handler with ack_policy=. Details

PolicyHandler returnsHandler raises
NACK_ON_ERRORdefaultackretryAt-least-once. Failures are retried, then dead-lettered.
ACK_ALWAYSackackFailures are logged and dropped, never retried.
ACK_FIRSTacked beforeacked beforeAt-most-once. A crash mid-handler loses the message.
MANUALyou call msg.ack()retryRillKit never acks. Return without acking and it is retried.

Around the handler

Middleware
Hooks for receiving, handling, publishing and cleanup. Idempotent ships in the box and skips duplicate deliveries.
Startup and shutdown hooks
on_startup, after_startup, on_shutdown and after_shutdown, as plain decorators on the broker.
Dicts or Pydantic
Handlers get the decoded JSON as a dict. Annotate the parameter with a Pydantic model and it is validated before your code runs. Pydantic is optional.
Graceful shutdown, heartbeat
SIGINT and SIGTERM let in-flight messages finish. Each consumer refreshes a heartbeat key, and active_workers() reads them.
Redis or Valkey, one server or a cluster
Through redis-py or valkey-py. On a cluster the stream, its DLQ and its heartbeats share one hash slot, so moving a message to the DLQ stays a single transaction.
Plain wire format
One JSON string in the data field of an ordinary stream entry. Anything that can XADD can publish, and anything that can XREADGROUP can read.

Nothing hidden. Look in the server.

Groups, pending entries and the dead-letter stream are ordinary stream structures. When something looks off at 2am, redis-cli or valkey-cli shows you what RillKit sees.

Acked
The entry is acked with XACK and leaves the pending list. lag: 0 means the group has read everything.
Waiting to retry
Still pending, with a delivery count. It is claimed again once it has been idle for claim_idle_ms times the backoff.
Dead-lettered
Copied to orders-dlq with the original body plus five x- fields saying where it came from and why it stopped.
redis-cli
127.0.0.1:6379> XINFO GROUPS orders
1)  1) "name"
    2) "workers"
    3) "consumers"
    4) (integer) 2
    5) "pending"
    6) (integer) 1
    7) "last-delivered-id"
    8) "1730032645250-0"
    9) "entries-read"
   10) (integer) 7
   11) "lag"
   12) (integer) 0

127.0.0.1:6379> XPENDING orders workers - + 10
1) 1) "1730032643012-0"
   2) "workers-web1-4242"
   3) (integer) 6210
   4) (integer) 2

127.0.0.1:6379> XRANGE orders-dlq - + COUNT 1
1) 1) "1730032645261-0"
   2) 1) "data"
      2) "{\"id\": 7, \"total\": -5}"
      3) "x-original-id"
      4) "1730032645250-0"
      5) "x-stream"
      6) "orders"
      7) "x-group"
      8) "workers"
      9) "x-error"
     10) "bad total"
     11) "x-deliveries"
     12) "1"

Running in about five minutes.

You need Python 3.9 or newer and a Redis or Valkey server you can reach. Local Docker is fine. The guide walks through the same steps with more explanation, then covers retries, the DLQ and running several workers.

terminal
# a server, if you do not have one (or redis:7)
$ docker run -d -p 6379:6379 valkey/valkey:8

$ pip install rillkit
$ export RILLKIT_URL=redis://localhost:6379/0

$ python worker.py   # terminal 1
$ python publish.py  # terminal 2

The RillKit SDKs are released under the Apache License 2.0.