47 releases

new 0.6.2 Dec 15, 2024
0.6.0 Nov 28, 2024
0.6.0-rc.5 Jul 25, 2024
0.5.1 Mar 13, 2024
0.2.0 May 14, 2021

#559 in Concurrency

Download history 4633/week @ 2024-08-26 6493/week @ 2024-09-02 3895/week @ 2024-09-09 4928/week @ 2024-09-16 3341/week @ 2024-09-23 2555/week @ 2024-09-30 3972/week @ 2024-10-07 4648/week @ 2024-10-14 4142/week @ 2024-10-21 4739/week @ 2024-10-28 5332/week @ 2024-11-04 4512/week @ 2024-11-11 4282/week @ 2024-11-18 3646/week @ 2024-11-25 3598/week @ 2024-12-02 3486/week @ 2024-12-09

15,095 downloads per month
Used in 9 crates (6 directly)

MIT license

135KB
3K SLoC

apalis

Simple, extensible multithreaded background job and messages processing library for Rust


Features

  • Simple and predictable task handling model.
  • Task handlers are just an async function with a macro free API.
  • Familiar dependency injection for task handlers, similar to actix and axum.
  • Take full advantage of the tower ecosystem of middleware, services, and utilities.
  • Easy to scale, backends are distributed by default.
  • Runtime agnostic - Use tokio, smol etc.
  • Inbuilt concurrency and parallelism.
  • Worker monitoring and graceful shutdown.
  • Ability to painlessly expose tasks and workers via APIs
  • Persisted cron jobs. Pipe your cronjobs to other backends and distribute them.
  • Optional Web interface to help you manage your jobs.

apalis job processing is powered by tower::Service which means you have access to the tower middleware.

apalis has support for:

Source Crate Example
Cron Jobs
Redis
Sqlite
Postgres
MySQL
Amqp
From Scratch

Getting Started

To get started, just add to Cargo.toml

[dependencies]
apalis = { version = "0.6" }
apalis-redis = { version = "0.6" }
# apalis-sql = { version = "0.6", features = ["postgres"] } # or mysql, sqlite

Usage

use apalis::prelude::*;
use apalis_redis::{RedisStorage, Config};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct Email {
    to: String,
}

/// A function that will be converted into a service.
async fn send_email(job: Email, data: Data<usize>) -> Result<(), Error> {
  /// execute job
  Ok(())
}

#[tokio::main]
async fn main() -> {
    std::env::set_var("RUST_LOG", "debug");
    env_logger::init();
    let redis_url = std::env::var("REDIS_URL").expect("Missing env variable REDIS_URL");
    let conn = apalis_redis::connect(redis_url).await.expect("Could not connect");
    let storage = RedisStorage::new(conn);
    Monitor::new()
        .register({
            WorkerBuilder::new(format!("email-worker"))
                .concurrency(2)
                .data(0usize)
                .backend(storage)
                .build_fn(send_email)
        })
        .run()
        .await
}

Then

//This can be in another part of the program or another application eg a http server
async fn produce_route_jobs(storage: &RedisStorage<Email>) -> Result<()> {
    let mut storage = storage.clone();
    storage
        .push(Email {
            to: "test@example.com".to_string(),
        })
        .await?;
}

Feature flags

  • tracing (enabled by default) — Support Tracing 👀
  • sentry — Support for Sentry exception and performance monitoring
  • prometheus — Support Prometheus metrics
  • retry — Support direct retrying jobs
  • timeout — Support timeouts on jobs
  • limit — 💪 Limit the amount of jobs
  • filter — Support filtering jobs based on a predicate
  • catch-panic - Catch panics that occur during execution

Storage Comparison

Since we provide a few storage solutions, here is a table comparing them:

Feature Redis Sqlite Postgres Sled Mysql Mongo Cron
Scheduled jobs x x
Retry jobs x x
Persistence x x BYO
Rerun Dead jobs x x x

How apalis works

Here is a basic example of how the core parts integrate

sequenceDiagram
    participant App
    participant Worker
    participant Backend

    App->>+Backend: Add job to queue
    Backend-->>+Worker: Job data
    Worker->>+Backend: Update job status to 'Running'
    Worker->>+App: Started job
    loop job execution
        Worker-->>-App: Report job progress
    end
    Worker->>+Backend: Update job status to 'completed'

External examples

Projects using apalis

  • Ryot: A self hosted platform for tracking various facets of your life - media, fitness etc.
  • Summarizer: Podcast summarizer
  • Universal Inbox: Universal Inbox is a solution that centralizes all your notifications and tasks in one place to create a unique inbox.
  • Hatsu: Self-hosted and fully-automated ActivityPub bridge for static sites.

Resources

Web UI

If you are running apalis Board, you can easily manage your jobs. See a working rest API example here

Thanks to

  • tower - Tower is a library of modular and reusable components for building robust networking clients and servers.
  • redis-rs - Redis library for rust
  • sqlx - The Rust SQL Toolkit
  • cron - A cron expression parser and schedule explorer

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Dependencies

~1.7–3MB
~57K SLoC