Guide

How to receive webhooks in Rust minimal receiver → production-ready processing

Start with a minimal “native” receiver, but don’t stop there. In production, reliable webhook handling means verification, retries, idempotency, and backpressure — which is where Hooque simplifies everything.

Building for a specific provider? Browse provider webhook APIs.

TL;DR

  • Treat “receive webhooks in Rust” as an ops problem, not just a route handler.
  • Verify the request before parsing/side effects (use a verifySignature(...) stub, then implement provider verification).
  • Return 2xx quickly; move work to a worker/queue to avoid timeouts and retries.
  • Assume retries and design idempotency (dedupe by event id + unique constraints).
  • Log + store raw payloads for replayable debugging.
  • If you need one workflow across many providers, centralize ingest + standardize consumption.

Deep dives: security, retries, queue migration.

Anti-patterns

  • Doing business logic inline in the Rust request handler.
  • Parsing/transforming the body before verification (breaks signing inputs).
  • Returning 2xx before authenticity is proven.
  • Skipping idempotency (retries become double side effects).

If you’re triaging a live incident, use the debugging playbook .

Framework shortcuts

If you’re already using a framework, jump straight to the minimal framework receiver, then reuse the same production guidance and Hooque consumer loops.

  1. Axum
    How to receive webhooks in Axum
  2. Actix Web
    How to receive webhooks in Actix Web
  3. Rocket
    How to receive webhooks in Rocket

Why it's hard in production

A route handler is the easy part. Supporting multiple senders means multiple security models, spikes, and retry semantics.

Verify authenticity + stop replays

Use a verifySignature(...) stub here, then implement real verification + replay defense for each provider.

Read the guide

Assume retries (duplicates are optional)

Treat every delivery as at-least-once and make side effects idempotent (DB constraints, dedupe keys).

Read the guide

Don’t do work in the request path

Ack fast, process async. Otherwise timeouts, deploys, and spikes turn into missed webhooks.

Read the guide

Debug with real payloads

Save the exact body + headers so you can replay deterministically after a fix.

Read the guide

Add monitoring + alerts early

Track delivered vs rejected, processing latency, queue depth, and error rates.

Read the guide

Iterate locally without losing events

Tunnels help, but durable capture + replay removes the “my laptop was asleep” problem.

Read the guide

Minimal receiver (Rust without a framework)

This is a minimal starting point. Keep verifySignature(...) as a stub here, then implement provider-specific verification and replay defense in the security guide .

// Rust doesn't include an HTTP server in the standard library.
// This example uses the tiny_http crate (small, no framework).
// Cargo.toml: tiny_http = "0.12"
use std::io::Read;
use tiny_http::{Method, Response, Server};

fn verify_signature(_headers: &std::collections::HashMap<String, String>, _body: &[u8]) {
  // don't compromise on security
  // TODO: implement provider-specific signature verification
}

fn process_data(_body: &[u8]) {
  // TODO: your business logic (DB writes, external API calls, etc.)
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
  let server = Server::http("0.0.0.0:3000")?;
  println!("listening on http://localhost:3000/webhooks");

  for mut request in server.incoming_requests() {
    if request.method() != &Method::Post || request.url() != "/webhooks" {
      let _ = request.respond(Response::empty(405));
      continue;
    }

    let mut body = Vec::new();
    // gracefully handle body streams that abort unexpectedly
    if let Err(e) = request.as_reader().read_to_end(&mut body) {
      eprintln!("failed to read body: {e}");
      let _ = request.respond(Response::empty(400));
      continue;
    }

    verify_signature(&Default::default(), &body);

    // What happens if it fails or times out?
    // Most providers retry -> duplicates unless you designed idempotency.
    process_data(&body);

    // IMPORTANT: ack fast to avoid timeouts and duplicate deliveries.
    let _ = request.respond(Response::from_string("ok"));
  }
  Ok(())
}

Hooque turns any webhook into a reliable queue.

Non-obvious scenario: you can’t expose a port

In real deployments, the hardest part is often “where does this endpoint run?” (NAT, corporate networks, locked-down environments, short-lived preview deployments). Hooque decouples inbound receiving from processing so your Rust app doesn’t need to be the public receiver.

The easy path: receive with Hooque + consume forever

Hooque turns inbound webhooks into a durable queue. Your code becomes a run-forever worker that pulls or streams events and acks/nacks/rejects explicitly.

  • No need to run a public webhook endpoint in every environment (especially for local dev).
  • Durable capture + replay/inspection so “we missed the webhook” becomes debuggable.
  • Explicit Ack / Nack / Reject lifecycle so retries are under your control.
  • Backpressure and spike absorption: buffer now, process at your pace.
  • One consumption pattern across many senders (even if their security/retry rules differ).

Flow

  1. Provider delivers → Hooque ingest endpoint
  2. Hooque persists payload immediately
  3. Your worker pulls (REST) or streams (SSE)
  4. Your worker ack/nack/rejects explicitly

Hooque REST polling loop (runs forever)

Polling is a good default when you want a simple worker loop. It also works in environments where long-lived connections are unreliable.

// Rust (reqwest + tokio)
// Runs forever: poll /next, ack/nack/reject explicitly.
// Cargo.toml:
// tokio = { version = "1", features = ["full"] }
// reqwest = { version = "0.12", features = ["json", "rustls-tls"] }
// serde_json = "1"
use serde_json::Value;
use std::time::Duration;

struct Msg {
    payload: Value,
    meta: Value,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let next_url = std::env::var("HOOQUE_QUEUE_NEXT_URL")
        .unwrap_or_else(|_| "https://app.hooque.io/queues/<consumerId>/next".to_string());
    let token = std::env::var("HOOQUE_TOKEN").unwrap_or_else(|_| "hq_tok_replace_me".to_string());
    let client = reqwest::Client::new();

    loop {
        match get_next_message(&client, &next_url, &token).await {
            Ok(Some(msg)) => {
                if let Err(e) = process_data(&msg.payload, &msg.meta) {
                    nack(&client, &msg, &token, e).await;
                } else {
                    ack(&client, &msg, &token).await;
                }
            }
            Ok(None) => tokio::time::sleep(Duration::from_secs(1)).await,
            Err(e) => {
                eprintln!("worker error: {e}");
                tokio::time::sleep(Duration::from_secs(2)).await;
            }
        }
    }
}

async fn get_next_message(client: &reqwest::Client, url: &str, token: &str) -> Result<Option<Msg>, Box<dyn std::error::Error>> {
    let resp = client.get(url).bearer_auth(token).send().await?;
    
    if resp.status() == reqwest::StatusCode::NO_CONTENT {
        return Ok(None);
    }
    if !resp.status().is_success() {
        return Err(format!("next() failed: {}", resp.status()).into());
    }

    let meta_raw = resp.headers().get("X-Hooque-Meta").and_then(|v| v.to_str().ok()).unwrap_or("{}");
    let meta: Value = serde_json::from_str(meta_raw).unwrap_or_else(|_| serde_json::json!({}));
    let raw = resp.text().await.unwrap_or_default();

    let payload = if let Ok(json) = serde_json::from_str::<Value>(&raw) { json } else { Value::String(raw) };
    
    Ok(Some(Msg { payload, meta }))
}

fn process_data(_payload: &Value, meta: &Value) -> Result<(), String> {
    println!("event: {}", meta["messageId"]);
    Ok(())
}

async fn ack(client: &reqwest::Client, msg: &Msg, token: &str) {
    if let Some(url) = msg.meta["ackUrl"].as_str() {
        let _ = client.post(url).bearer_auth(token).send().await;
    }
}

async fn nack(client: &reqwest::Client, msg: &Msg, token: &str, err: String) {
    let url = msg.meta["nackUrl"].as_str().or_else(|| msg.meta["rejectUrl"].as_str());
    if let Some(url) = url {
        let _ = client.post(url).bearer_auth(token).json(&serde_json::json!({ "reason": err })).send().await;
    }
}

Hooque SSE stream consumer (runs forever)

SSE is great for low-latency processing: keep a connection open, process events as they arrive, and reconnect on disconnects.

// Rust — SSE consumer (reqwest + tokio)
// Runs forever: connect to /stream, handle "message" events, ack/nack/reject explicitly.
// Cargo.toml:
// tokio = { version = "1", features = ["full"] }
// reqwest = { version = "0.12", features = ["rustls-tls"] }
// serde_json = "1"
use serde_json::Value;
use std::time::Duration;
use tokio::sync::mpsc;

struct Msg {
    payload: Value,
    meta: Value,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let stream_url = std::env::var("HOOQUE_QUEUE_STREAM_URL")
        .unwrap_or_else(|_| "https://app.hooque.io/queues/<consumerId>/stream".to_string());
    let token = std::env::var("HOOQUE_TOKEN").unwrap_or_else(|_| "hq_tok_replace_me".to_string());
    let client = reqwest::Client::builder().timeout(None).build()?;

    let (tx, mut rx) = mpsc::channel::<Msg>(100);

    let client_clone = client.clone();
    let token_clone = token.clone();
    tokio::spawn(async move {
        loop {
            get_message_stream(&client_clone, &stream_url, &token_clone, tx.clone()).await;
            tokio::time::sleep(Duration::from_secs(2)).await;
        }
    });

    while let Some(msg) = rx.recv().await {
        if let Err(e) = process_data(&msg.payload, &msg.meta) {
            nack(&client, &msg, &token, e).await;
        } else {
            ack(&client, &msg, &token).await;
        }
    }

    Ok(())
}

async fn get_message_stream(client: &reqwest::Client, url: &str, token: &str, tx: mpsc::Sender<Msg>) {
    let resp = client.get(url).bearer_auth(token).header("Accept", "text/event-stream").send().await;
    let mut resp = match resp {
        Ok(r) if r.status().is_success() => r,
        Ok(r) => { eprintln!("stream failed: {}", r.status()); return; }
        Err(e) => { eprintln!("stream error: {e}"); return; }
    };

    let mut buf = String::new();
    let mut event: Option<String> = None;
    let mut data_lines: Vec<String> = Vec::new();

    loop {
        let chunk = match resp.chunk().await {
            Ok(Some(c)) => c,
            Ok(None) | Err(_) => break,
        };

        buf.push_str(&String::from_utf8_lossy(&chunk));
        while let Some(idx) = buf.find('\n') {
            let mut line = buf[..idx].to_string();
            buf.drain(..=idx);
            
            if line.ends_with('\r') { line.pop(); }
            if line.starts_with(':') { continue; }
            if line.is_empty() {
                if event.as_deref() == Some("message") && !data_lines.is_empty() {
                    let data = data_lines.join("\n");
                    if let Ok(raw_msg) = serde_json::from_str::<Value>(&data) {
                        let _ = tx.send(Msg {
                            payload: raw_msg["payload"].clone(),
                            meta: raw_msg["meta"].clone()
                        }).await;
                    }
                }
                event = None;
                data_lines.clear();
                continue;
            }
            if let Some(v) = line.strip_prefix("event:") { event = Some(v.trim().to_string()); }
            if let Some(v) = line.strip_prefix("data:") { data_lines.push(v.trim_start().to_string()); }
        }
    }
}

fn process_data(_payload: &Value, meta: &Value) -> Result<(), String> {
    println!("event: {}", meta["messageId"]);
    Ok(())
}

async fn ack(client: &reqwest::Client, msg: &Msg, token: &str) {
    if let Some(url) = msg.meta["ackUrl"].as_str() {
        let _ = client.post(url).bearer_auth(token).send().await;
    }
}

async fn nack(client: &reqwest::Client, msg: &Msg, token: &str, err: String) {
    let url = msg.meta["nackUrl"].as_str().or_else(|| msg.meta["rejectUrl"].as_str());
    if let Some(url) = url {
        let _ = client.post(url).bearer_auth(token).json(&serde_json::json!({ "reason": err })).send().await;
    }
}

FAQ

Quick answers for the questions that come up right before you ship.

What status code should I return for webhooks in Rust?

General: Usually return a fast 2xx after validating authenticity and basic schema. Timeouts and 5xx commonly trigger retries.

How Hooque helps: Hooque acknowledges ingest immediately and persists the payload. Your worker acks/nacks/rejects explicitly after processing.

Do I need signature verification in Rust?

General: Yes, unless the sender is fully trusted and on a private network. A public endpoint without verification is easy to forge and easy to replay.

How Hooque helps: Hooque can verify at ingest for supported providers or using generic strategies. Either way, your worker receives a normalized meta object and can stay focused on processing.

Why do I see duplicate webhook events in Rust?

General: Retries are normal: timeouts, transient network failures, and 5xx responses all produce duplicates. Design idempotency around event ids and side-effect boundaries.

How Hooque helps: Hooque makes delivery outcomes explicit (ack/nack/reject) and provides replay/inspection so you can fix issues without guessing what was received.

How do I test webhooks locally in Rust?

General: You can use a tunnel, but local dev still breaks on sleep, VPNs, clock skew, and signature-byte mismatches.

How Hooque helps: With Hooque you can avoid inbound locally: receive events into a durable queue and pull/stream to your laptop, then replay from the UI after changes.

Should I use REST polling or SSE streaming for webhook processing?

General: Use REST polling for simple batch workers and environments without long-lived connections. Use SSE for low-latency “process as it arrives” flows.

How Hooque helps: Hooque supports both: `GET /next` for polling and `GET /stream` for streaming. Both include meta with ready-to-call ack/nack/reject URLs.

Start processing webhooks reliably

Create a webhook endpoint, receive events, then run your worker forever using REST polling or SSE streaming — with explicit ack/nack/reject control.

No credit card required