Tasks and their results, over Redis Streams

A Rust library for handing work to other programs: a producer adds a task to a stream, a worker takes it and holds a lease while it runs, and the result comes back on a stream of its own.

It speaks an existing work contract over Redis Streams that a PHP producer and Python workers already exchange, so a Rust program can take part on either side. Its README is the public statement of that contract, version 1.

It is a plain library, with blocking calls and threads and no async runtime. It is not a general job queue with a format of its own. And it is not a security boundary: every program that can write to the Redis instance is trusted.

Version
0.1.1, on crates.io
Reference
docs.rs/legit-streams
Source
github.com/mferrara/legit-rs
Licence
MIT
Needs
Rust 1.99 or newer, and Redis 6.2 or newer; it has been run against Redis 8.0.5, and not against 6.2. Three dependencies: redis, tracing and ulid. No type of the redis crate appears in its own API.

Running on this server

This site uses the crate it describes. Beside its web server run a Redis of its own and one worker: legit-hasher, a published program whose worker mode is built on this crate. The web process sends it tasks of that program's kind, hash: hash a short text with simhash-v1. This is that rig at work.

Send a task

What you type travels in this page's address, so it reaches the server's log like any address does. It also passes through the site's own Redis on its way to the worker, and is deleted there once the worker has answered it, or, if none answered in time, when a worker next reads it and discards it. Up to 200 characters; don't paste anything private.

The bulk lane, every 15 seconds

Nobody waits on the bulk lane, so the site keeps it moving itself. Every 15 seconds the web process adds one task to hash_tasks, naming its own result stream, and reads the result once the worker has written it. These are the counts since the web process answering you started, 2 hours 50 minutes ago. A task in flight when the worker or the Redis restarts, as each does now and then, may never be answered, so the two counts need not match: the difference is not a queue.

Bulk tasks sent
682
Results read
682
The last one, from sent to result read
684 µs
Visitors' tasks on the fast lane
0
Their middle round trip
none yet

These are the numbers as this page was served.

A task's life

A task passes through Redis twice: as a task on a task stream, and as a result on a result stream. Workers read the task stream through one consumer group, so each task goes to one worker.

Producer Task stream Worker Result stream Reader add take lease, renewed every 60 s result ack, delete read 1 2 3 4 5 6
Time runs down. A dot is an entry added to a stream; its line runs until the entry is deleted. The worker's bar is its lease, one block for each 60 s, the default time between renewals.
  1. The producer adds the task to the task stream with XADD. It refuses once 300 tasks are waiting, by default.
  2. A worker in the group takes it. Redis keeps the entry in the group's pending list, with its owner, how long it has sat idle and how many times it has been delivered.
  3. While the task runs, the worker renews its lease every 60 s by default, in one atomic step on the server. If the entry is no longer pending for this worker, the lease is lost: the worker stops, writes no result, and neither acknowledges nor deletes the entry.
  4. When the work is done, the worker adds a result to the stream the task names in reply_to. A task that names none, or names one that is not valid, has its result on the worker's default result stream.
  5. Then it acknowledges and deletes the task, with XACK and XDEL, in that order.
  6. The application reads its result stream through a consumer group, handles each result, then acknowledges and deletes it.

Results arrive at least once: a crash between writing a result and acknowledging the task repeats the result, so whatever reads results must cope with the same task_id twice.

A task the worker cannot read, for instance because a required field is missing, its task_id is outside the allowed characters or the entry is over its size bounds, is never run and never left pending. If it has a non-empty task_id, it is answered with an invalid_task error result and removed; if it has none, it is logged and removed. A task written for another version of the contract is answered with unsupported_version. The delivery count is checked first, before the entry is read, so an entry that breaks a worker while it is being read is stopped too.

When a worker dies or stalls, its task is not lost. Before each read, every worker claims entries that have sat idle for the claim threshold, 300 s by default, with XAUTOCLAIM. Every worker on a group must use the same threshold, and every one must renew leases: this crate's workers would claim the running tasks of a worker that does not.

Task stream Workers Result stream take delivery 1 idle 300 s claim delivery 2 claim delivery 3 claim delivery 4 error result ack, delete 1 2 3 4
Time runs down, at the same scale as above: a block of lease is 60 s and the idle stretch 300 s, both defaults. A cross marks where a worker dies.
  1. A worker takes the task, renews its lease once, and dies.
  2. The entry stays pending, its idle time growing from the last renewal.
  3. Once it has sat idle for the claim threshold, another worker claims it and runs it again. Each claim counts a delivery. Here the task kills that worker too, and the next.
  4. A task runs on deliveries 1 to 3, by default. Taken a fourth time, it is not run: the worker writes an error result, max_deliveries_exceeded, then acknowledges and deletes the task. A task that kills its worker cannot kill them all.

A worker that stops cleanly does not make the next one wait. It gives its running tasks up to 30 s by default, then releases any still running, so the next XAUTOCLAIM takes them at once. A handler can release its own task the same way. Each release is followed by a claim, and each claim counts a delivery, so a task released three times reaches the delivery limit. A released task can be claimed at once, while its first handler is still running: a long handler calls context.checkpoint() to notice that it has been released, and every handler must tolerate a task that runs twice.

The fast lane

The fast lane is for small tasks a caller waits for. The caller sends a task on the lane's own task stream, with a reply key named after the task and a deadline, and blocks on that key. Each fast lane has a kind, which names its reply keys, and a fast worker answers only reply keys of its own kind. A fast worker never claims, leases or retries: a fast task is answered once or not at all.

Caller Fast task stream Fast worker Reply key add read reply expires after 60 s ack, delete read deadline 1 2 3 4 5
Time runs down. The hollow bar is the caller waiting, and the dashed line is its deadline.
  1. The caller adds the task to the fast task stream, with its own reply key, results:{app}:{kind}:rpc:{task_id}, in reply_to, and a deadline in deadline_ms. Then it waits on the key.
  2. A fast worker reads the task. One with any other reply key, or past its deadline, is removed unanswered. Every other task gets exactly one reply, success or error, even when the worker is stopping.
  3. The worker adds its result to the reply key and sets the key to expire 60 s later, by default.
  4. Then it acknowledges and deletes the task.
  5. The caller reads the key from its start, so a reply that came before the read is still seen, then deletes the key. Anything on the key that is not its own task's result is not a reply: the caller reads past it and keeps waiting.

If the deadline comes first, call returns Error::Timeout, having deleted its task and its reply key. The caller falls back, to a slower path or an error for its user, and never sends the task again.

Using it

[dependencies]
legit-streams = "0.1"

A first run

The repository has three examples for a made-up kind of task, length, whose worker answers each task with the length of its text. Run as they are, they use the crate's in-memory double and need no server. With REDIS_URL set, they use a real one. In a first terminal, start a throwaway Redis:

docker run --rm -p 6379:6379 redis:8

In a second, from a checkout of the crate, start the worker. It creates its consumer group, serves length_tasks for a minute, then stops cleanly:

REDIS_URL=redis://127.0.0.1:6379 cargo run --example worker

In a third, within that minute, send three tasks and wait for their results:

REDIS_URL=redis://127.0.0.1:6379 cargo run --example producer

The producer prints each task it sends, then each result as the worker answers it. The order does not matter: tasks sent before the worker starts wait in the stream, and the producer waits up to 30 s for its results. The third example, fast, runs a fast worker and a caller waiting for its reply, in one process.

Names

Each kind of work has a name of 1 to 16 lowercase letters, digits, _ and -, and its keys are named after it. One worker group reads both of a kind's task streams, and a result goes to the default result stream when its task names no reply stream. That default serves a Redis instance with a single application: with more than one, every producer must send reply_to and every worker must honour it.

Kind hash, application app
What Name
Task streamhash_tasks
Worker grouphash_workers
Default result streamhash_results
Application's result streamresults:app:hash
Fast task streamhash_tasks:fast
Fast reply keyresults:app:hash:rpc:{task_id}

The kind in the table is a real one: legit-hasher is a worker of this contract and serves the kind hash.

A deployment may put a constant prefix in front of every key, as many frameworks do for a connection: RedisStreams::open(url)?.with_key_prefix("app_") adds it to every key the crate names. Names inside entries, such as reply_to, are written without it, and group and consumer names are never prefixed.

A worker

A worker for the examples' kind, length, running four tasks at once: its handler answers with the length of the text. The repository's examples/worker.rs is a fuller worker of the same kind.

use legit_streams::{
    Context, Failure, RedisStreams, Reply, Task, Worker, WorkerConfig,
};

fn length(task: &Task, context: &Context) -> Result<Reply, Failure> {
    // The kind's required payload; without it the task is `invalid_task`...
    let text = task
        .get("text_data")
        .ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
    if !task.model_name().is_empty() && task.model_name() != "example/length" {
        return Err(Failure::new(
            "unsupported_model",
            format!("no model `{}`", task.model_name()),
        )
        .field("supported_models", "[\"example/length\"]"));
    }
    context.checkpoint()?;
    Ok(Reply::new().field("result", text.len().to_string()))
}

fn main() -> legit_streams::Result<()> {
    let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
    let config = WorkerConfig {
        concurrency: 4,
        ..WorkerConfig::new(
            "length_tasks",
            "length_workers",
            "length-worker-host1_4242",
            "length_results",
        )
    };
    let running = Worker::new(config, streams, length)?.spawn()?;

    // Stop on a signal or when the work runs out; here, after a minute...
    std::thread::sleep(std::time::Duration::from_secs(60));
    running.stop();
    let report = running.join()?;
    println!("{} results, {} released", report.results, report.released.len());
    Ok(())
}

A panic in the handler is caught and answered with an internal error, and the loop goes on.

A producer and a result reader

use std::time::Duration;
use legit_streams::{Error, Producer, RedisStreams, ResultReader, Task};

fn main() -> legit_streams::Result<()> {
    let streams = RedisStreams::open("redis://127.0.0.1:6379")?;

    let task = Task::builder("app", "post", "42")
        .model_name("example/length")
        .reply_to(legit_streams::reply_to("app", "length"))
        .field("text_data", "Where is the station?")
        .build()?;
    match Producer::new(streams.clone(), "length_tasks").send(&task) {
        Ok(id) => println!("sent {} as entry {id}", task.task_id()),
        Err(Error::StreamFull { depth, .. }) => {
            println!("{depth} tasks waiting; try again later")
        }
        Err(error) => return Err(error),
    }

    let reader = ResultReader::new(streams, "results:app:length", "app", "app-host1");
    for received in reader.read(25, Some(Duration::from_secs(5)))? {
        match &received.result {
            Ok(result) if result.is_success() => {
                println!("{}: {:?}", result.task_id(), result.get("result"))
            }
            Ok(result) => println!(
                "{} failed: {:?} {:?}",
                result.task_id(),
                result.error_type(),
                result.error()
            ),
            Err(error) => println!("entry {} isn't a result: {error}", received.id),
        }
        reader.ack(&[received.id])?;
    }
    // Results a crashed reader left unacknowledged for five minutes, each with its
    // delivery count...
    for stranded in reader.reclaim(Duration::from_secs(300), 25)? {
        println!("entry {} delivered {:?} times", stranded.id, stranded.deliveries);
    }
    Ok(())
}

The producer refuses with Error::StreamFull once the task stream holds 300 entries, by default: payloads travel inside the entries, so a stream's depth is its memory use.

Who to trust

Every party that can write to the Redis instance is trusted. Nothing in the contract binds a reply to its caller or a task to its sender:

The control is the instance's access rules (ACLs), not the envelope. Do not expose the Redis to untrusted writers. Give producers no read access to task streams, so a task_id stays as good as a reply token, and let each application write only its own task fields and read only its own result keys.

A fast task's task_id must carry at least 64 random bits, since its reply key is named after it and an id another party can guess is a key it can answer. The ids the crate generates do.

A worker also refuses an entry with more than 256 fields, a field name over 256 bytes, or more than 64 MiB of names and values together, but only once Redis has delivered it. The bounds keep a hostile entry from a handler and off a result stream, not out of memory.

What was measured

The crate's tests run on an in-memory double of the stream commands. In one run on 2 December 2026, the double and the crate were checked against a real server.

Against Redis 8.0.5, one run
Check Result
Stream commands, double against server72 of 72 the same
Worker scenarios on the server14 of 14 passed
Fast-lane scenarios on the server10 of 10 passed
All three again with a key prefix, and 6 checks of the prefix itselfThe same, and all passed
Fast-lane round trip, median206 µs
Fast-lane round trip, 99th percentile463 µs

The commands include the lease scripts, run by the owner, by another worker, and after the entry was acknowledged or deleted, and a group's backlog as XINFO GROUPS reports it after adds, reads, acknowledgements and a claim. The scenarios include a dead worker's task run again, the delivery limit, a lease lost while a result is being written, and shutdown releasing running tasks to other workers. It has not been run against Redis 6.2, the oldest version it needs.

The round trip is 10,000 calls made one at a time, after 100 to warm up, to a handler that answers at once, with the server and the client on one machine. It measures the client, the server and the machine together, so expect other numbers elsewhere. No figure here is for throughput under load, for several workers at once, or for the bulk lane.

What it does not do

The README has the full contract: every field, the lengths and characters allowed, the settings and their defaults, and every error type.