Actix-web is a high-performance Rust web framework built on Tokio. The uuid crate provides UUID v4 and v7 generation with the v4 and v7 feature flags. UUID v7’s monotonic ordering reduces B-tree index fragmentation in PostgreSQL — important for high-throughput Actix-web services. See UUID in Rust for the crate overview.

Cargo.toml setup

[dependencies]
actix-web = "4"
uuid = { version = "1", features = ["v7", "serde"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "uuid"] }
tokio = { version = "1", features = ["full"] }

Handler with UUID v7 path parameter

use actix_web::{get, post, web, HttpResponse, Responder};
use uuid::Uuid;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Order {
    id: Uuid,
    customer_id: String,
    total: f64,
}

#[derive(Deserialize)]
struct CreateOrder {
    customer_id: String,
    total: f64,
}

// POST /orders — generate UUID v7 for the new order
#[post("/orders")]
async fn create_order(
    body: web::Json<CreateOrder>,
    db: web::Data<sqlx::PgPool>,
) -> impl Responder {
    let order = Order {
        id: Uuid::now_v7(),
        customer_id: body.customer_id.clone(),
        total: body.total,
    };

    sqlx::query!(
        "INSERT INTO orders (id, customer_id, total) VALUES ($1, $2, $3)",
        order.id,
        order.customer_id,
        order.total,
    )
    .execute(db.get_ref())
    .await
    .unwrap();

    HttpResponse::Created().json(&order)
}

// GET /orders/{id} — UUID path parameter, automatically validated
#[get("/orders/{id}")]
async fn get_order(
    path: web::Path<Uuid>,
    db: web::Data<sqlx::PgPool>,
) -> impl Responder {
    let id = path.into_inner();

    let row = sqlx::query_as!(
        Order,
        "SELECT id, customer_id, total FROM orders WHERE id = $1",
        id
    )
    .fetch_optional(db.get_ref())
    .await
    .unwrap();

    match row {
        Some(order) => HttpResponse::Ok().json(order),
        None => HttpResponse::NotFound().finish(),
    }
}

Middleware: UUID v7 trace ID per request

use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::Error;
use futures::future::{ok, Ready};
use uuid::Uuid;

pub struct TraceId;

impl<S, B> Transform<S, ServiceRequest> for TraceId
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Transform = TraceIdMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(TraceIdMiddleware { service })
    }
}

pub struct TraceIdMiddleware<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for TraceIdMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
{
    // ... call() injects UUID v7 trace ID into request extensions
    // and sets X-Trace-Id response header
}

Request-scoped UUID v7 trace IDs sort chronologically in log aggregators — no separate timestamp field needed. See UUID v7 in Microservices.

Cursor pagination with UUID v7

#[derive(Deserialize)]
struct PaginationParams {
    cursor: Option<Uuid>,
    limit: Option<i64>,
}

#[get("/orders")]
async fn list_orders(
    query: web::Query<PaginationParams>,
    db: web::Data<sqlx::PgPool>,
) -> impl Responder {
    let limit = query.limit.unwrap_or(20).min(100);

    let orders = if let Some(cursor) = query.cursor {
        sqlx::query_as!(
            Order,
            "SELECT id, customer_id, total FROM orders WHERE id > $1 ORDER BY id LIMIT $2",
            cursor,
            limit,
        )
        .fetch_all(db.get_ref())
        .await
        .unwrap()
    } else {
        sqlx::query_as!(
            Order,
            "SELECT id, customer_id, total FROM orders ORDER BY id LIMIT $1",
            limit,
        )
        .fetch_all(db.get_ref())
        .await
        .unwrap()
    };

    HttpResponse::Ok().json(orders)
}

UUID v7 cursors are stable and opaque — they encode creation time but expose no sensitive information. See UUID v7 for Cursor Pagination.

Idempotency key validation

use actix_web::HttpRequest;
use uuid::Uuid;

fn extract_idempotency_key(req: &HttpRequest) -> Option<Uuid> {
    req.headers()
        .get("Idempotency-Key")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| Uuid::parse_str(s).ok())
}

See UUID as Idempotency Keys for the full retry-safe API pattern.

Further reading

External references

Frequently asked questions

How do I generate UUID v7 in Rust and Actix-web?

Add uuid = { version = "1", features = ["v7"] } to your Cargo.toml. Generate with Uuid::now_v7(). The uuid crate uses getrandom for cryptographically secure random bits. See UUID in Rust for the full crate guide.

How do I use UUID as an Actix-web path parameter?

Use web::Path<Uuid> as the handler parameter type. Actix-web will automatically parse and validate the UUID from the path segment using the uuid crate's FromStr implementation. Invalid UUID strings return a 400 automatically.

How do I store UUID v7 in PostgreSQL from Actix-web?

With SQLx: use the sqlx = { version = "0.8", features = ["postgres", "uuid"] } feature. Bind Uuid directly in queries. With Diesel: use diesel-uuid or Diesel's built-in uuid feature. UUID v7 values are stored in PostgreSQL's native uuid type (16 bytes). See UUID in Rust.