Monitoring Rust Actix-Web Services: Deploy Lescopr Agent for End‑to‑End Latency

Close-up photograph of colorful source code and a terminal displayed on a computer monitor in a dark workspace. The angled perspective and shallow depth of field create a cinematic look, highlighting
Step‑by‑step guide to instrument an Actix‑Web service with Lescopr, capture latency across the stack, and visualize end‑to‑end performance.

Introduction

Performance regressions in Rust microservices built with Actix‑Web often surface as increased response times or higher error rates. Without fine‑grained observability, pinpointing the exact stage—whether it’s a handler, a database query, or an external HTTP call—can become a time‑consuming guessing game. This guide walks you through a complete project, from creating a minimal Actix‑Web service to deploying the Lescopr Agent, configuring end‑to‑end latency collection, and visualising the results on a dashboard. By the end, you will have a production‑ready monitoring setup that reduces mean time to resolution (MTTR) and helps you meet service‑level agreements (SLAs).


1. Project Setup – Defining the Scope

1.1 Choose the Stack

  • Language: Rust 1.70+ (stable)
  • Web framework: Actix‑Web 4.x
  • Database: PostgreSQL via sqlx
  • External API: Mocked JSON placeholder
  • Observability: Lescopr Agent (Rust SDK)

1.2 Milestone 1 – Scaffold the Service

Create a new Cargo project and add the required dependencies:

cargo new actix_lens_demo --bin
cd actix_lens_demo
cat >> Cargo.toml <<EOF
actix-web = "4"
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-native-tls"] }
reqwest = { version = "0.11", features = ["json"] }
lescopr = "0.3"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
env_logger = "0.10"
EOF

Initialize a basic main.rs that starts an HTTP server on port 8080 and defines a single /health endpoint. This baseline will be used to verify that the service runs correctly before any instrumentation.


2. Instrumenting the Application

2.1 Why Instrument?

Answer: Instrumentation provides the data needed to calculate end‑to‑end latency—the total time from the moment a client sends a request until the final response leaves the server. Without it, you only see coarse metrics like request count or error rate.

2.2 Adding Lescopr SDK

Add the Lescopr initialization at the start of main:

use lescopr::prelude::*;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Initialise logger
    env_logger::init();

    // Initialise Lescopr Agent
    let tracer = LescoprTracer::builder()
        .service_name("actix_lens_demo")
        .environment("production")
        .build()
        .expect("Failed to initialise Lescopr tracer");

    // Wrap the Actix server with the tracer middleware
    HttpServer::new(move || {
        App::new()
            .wrap(tracer.clone())
            .route("/health", web::get().to(health))
            .route("/users/{id}", web::get().to(get_user))
    })
    .bind("0.0.0.0:8080")?
    .run()
    .await
}

The wrap(tracer.clone()) middleware automatically creates a span for each incoming request, capturing start and end timestamps. It also propagates context to downstream async calls, enabling full trace continuity.

2.3 Tracing Database Calls

Wrap each SQL query in a Lescopr span to measure query latency:

async fn get_user(db: web::Data<PgPool>, path: web::Path<i32>) -> impl Responder {
    let user_id = path.into_inner();
    let span = lescopr::span!("db_query", "Fetching user from DB");
    let row = sqlx::query!("SELECT id, name FROM users WHERE id = $1", user_id)
        .fetch_one(&**db)
        .await;
    span.end(); // Record query duration
    match row {
        Ok(r) => HttpResponse::Ok().json(r),
        Err(_) => HttpResponse::NotFound().finish(),
    }
}

2.4 Tracing External HTTP Calls

When the service calls an external API, create a child span:

async fn fetch_remote_data() -> Result<serde_json::Value, reqwest::Error> {
    let span = lescopr::span!("http_outbound", "Call remote JSON API");
    let resp = reqwest::get("https://jsonplaceholder.typicode.com/todos/1").await?;
    let json = resp.json().await?;
    span.end();
    Ok(json)
}

By nesting spans, Lescopr can compute the cumulative latency and also break it down by component.


3. Deploying the Service

3.1 Containerisation

Create a Dockerfile that builds the binary and runs it with the Lescopr Agent environment variables:

FROM rust:1.70 as builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:stable-slim
COPY --from=builder /app/target/release/actix_lens_demo /usr/local/bin/actix_lens_demo
ENV LESCOPR_API_KEY=YOUR_API_KEY
ENV LESCOPR_ENDPOINT=https://api.lescopr.io/collect
EXPOSE 8080
CMD ["/usr/local/bin/actix_lens_demo"]

Build and push the image to your registry:

docker build -t myrepo/actix_lens_demo:latest .
docker push myrepo/actix_lens_demo:latest

3.2 Kubernetes Manifest

Deploy the container with a simple Deployment and Service:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: actix-lens-demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: actix-lens-demo
  template:
    metadata:
      labels:
        app: actix-lens-demo
    spec:
      containers:
        - name: actix
          image: myrepo/actix_lens_demo:latest
          ports:
            - containerPort: 8080
          env:
            - name: LESCOPR_API_KEY
              valueFrom:
                secretKeyRef:
                  name: lescopr-secret
                  key: api_key
            - name: LESCOPR_ENDPOINT
              value: "https://api.lescopr.io/collect"
---
apiVersion: v1
kind: Service
metadata:
  name: actix-lens-demo-svc
spec:
  selector:
    app: actix-lens-demo
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

Apply the manifests:

kubectl apply -f k8s.yaml

3.3 Verifying the Deployment

After the pods are running, send a request to the /users/1 endpoint and check the Lescopr dashboard for a new trace. The trace should display three nested spans: HTTP inbound, DB query, and HTTP outbound (if the handler calls the remote API). The total duration shown is the end‑to‑end latency.


4. Analysing Latency on the Lescopr Dashboard

4.1 Key Metrics

  • Request latency (p95) – shows the 95th percentile response time.
  • Database query time – isolates slow queries.
  • External call latency – helps negotiate third‑party SLAs.
  • Error rate – correlates spikes with latency changes.

4.2 Setting Alerts

Configure an alert in Lescopr to trigger when p95 latency exceeds 250 ms for more than five minutes. The alert can be sent to Slack or PagerDuty, ensuring the SRE team reacts before users notice degradation.


5. Optimisation Loop – From Data to Action

  1. Identify the bottleneck – Use the trace breakdown to see which span consumes the most time.
  2. Apply targeted fixes – For a slow DB query, add an index; for a lagging external call, implement caching or circuit‑breaker logic.
  3. Re‑measure – Deploy the change and observe the latency reduction on the dashboard.
  4. Iterate – Repeat the cycle until latency meets the SLA target.

By keeping the feedback loop tight, you can shave milliseconds off each request, directly improving user experience and reducing operational cost.


Conclusion

Integrating the Lescopr Agent with an Actix‑Web service provides end‑to‑end visibility that is essential for modern Rust applications. The step‑by‑step workflow—from scaffolding the project, instrumenting code, containerising, and deploying to Kubernetes—demonstrates a repeatable pattern for any microservice in your fleet. With precise latency data, you can make informed optimisation decisions, lower MTTR, and uphold SLA commitments.

To go further, Lescopr's documentation covers step‑by‑step setup.


Reading time: 8 minutes


Feature image alt: "Rust code running on a server with a monitoring dashboard"