Skip to main content

Crate asyncq_postgres

Crate asyncq_postgres 

Source
Expand description

PostgreSQL backend for asyncq.

§Quick start

use asyncq::{Queue, Worker, Job, Perform, JobContext, JobResult};
use asyncq_postgres::PostgresBackend;
use serde::{Serialize, Deserialize};

#[derive(Job, Serialize, Deserialize)]
#[job(queue = "emails", retries = 3)]
struct SendEmail { to: String }

impl Perform for SendEmail {
    async fn perform(self, _ctx: JobContext) -> JobResult {
        println!("Sending to {}", self.to);
        Ok(())
    }
}

#[tokio::main]
async fn main() {
    let backend = PostgresBackend::new("postgres://user:pass@localhost/mydb").await.unwrap();
    backend.migrate().await.unwrap();

    let queue = Queue::new(backend);
    queue.enqueue(SendEmail { to: "user@example.com".into() }).await.unwrap();
    Worker::new(queue).register::<SendEmail>().run().await;
}

§Transactional outbox

PostgreSQL enables the transactional outbox pattern natively: enqueue a job in the same transaction as your business logic. The job only becomes visible to workers after tx.commit() — if the transaction rolls back, the job disappears with it.

ⓘ
use asyncq_postgres::PostgresBackend;
use chrono::Utc;
use serde_json::json;

async fn create_order(backend: &PostgresBackend, pool: &sqlx::PgPool) -> anyhow::Result<()> {
    let mut tx = pool.begin().await?;

    sqlx::query("INSERT INTO orders (status) VALUES ('pending')")
        .execute(&mut *tx).await?;

    // Enqueue in the same transaction
    backend.enqueue_in_tx(
        "order.created",          // job kind — must match a registered Job type
        "orders",                 // queue name
        serde_json::to_vec(&json!({"order_id": 1}))?,
        3,                        // max_attempts
        Utc::now(),               // scheduled_at (now = run immediately)
        &mut tx,
    ).await?;

    tx.commit().await?;           // job visible to workers only after this
    Ok(())
}

Structs§

PostgresBackend
PostgreSQL backend for asyncq.