anantbhandarkar/make-it-right/mir-backend-rust-actix

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Make It Right (Actix-web module). Actix-web 4.x + async Rust specific reliability augmentation. Use alongside mir-backend and mir-backend-rust when the target stack is Actix-web — it carries the mechanical footguns that the framework-agnostic tiers deliberately omit: the multi-worker app data trap (state constructed inside the App factory closure yields N independent copies, not one shared instance), web::Data<T> Arc semantics versus web::ThinData, the removed .data() method, worker-local single-threaded actix-rt execution (!Send types allowed, guard-across-await compiles and deadlocks, blocking starves the whole worker), web::block for blocking work, the real default body limits behind JsonConfig and PayloadConfig, Route::wrap ordering that used to silently drop route middleware, and error handling via the ResponseError trait. TRIGGER only when the Rust backend framework is Actix-web — building, reviewing, or debugging an Actix-web handler, middleware, extractor, or App factory. Always loads TOGETHER WITH mir-backend (the gates) and mir-backend-rust (Tokio runtime concerns: blocking, cancellation safety, async traits, Arc/'static, backpressure, timeouts); this module only adds Actix-web library mechanics. SKIP for Axum — route syntax, extractor ordering, State/FromRef, IntoResponse and Tower layers belong to mir-backend-rust-axum, not here. SKIP for Warp, Poem, or any non-Actix Rust stack, and for non-Rust runtimes.

Install

npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-rust-actix

SKILL.md

The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-rust-actix.

/mir-backend-rust-actix · Make It Right (Actix-web)

Bottom tier of the chain: mir-backend (generic gates) → mir-backend-rust (Tokio runtime model) → this (Actix-web library mechanics). Run the gates first; load the Rust runtime tier for blocking/cancellation/Arc concerns; reach for this at Gate 5 (design mechanics), Gate 6 (implementation), and Gate 7 review. Runtime-level concerns (blocking the async runtime, cancellation safety, bounded channels, timeouts) live in `mir-backend-rust` — not here.

Stack assumed: Actix-web 4.x · actix-rt (Tokio-backed single-threaded workers) · async Rust.

Versions verified 13 Aug 2026:

CrateCurrentNote
actix-web4.14.1 (2026-08-09)MSRV 1.88 since 4.13.0. Still 4.x — there is no Actix-web 5
actix-files0.6.10 (2026-02-06)0.6.10 was a security release — see the Security section
actix-cors0.7.1ships an unsafe preset — see the Security section
actix-session0.11.0

Actix-web 4 has been stable for years and the 4.x line is where all work lands. If you see HttpServer::new returning App with .data(...), that is 3.x-era code and will not compile.

The Actix-web footguns AI walks into most

1. The multi-worker App Data trap — the defining Actix footgun

HttpServer::new accepts a closure (the App factory) and calls it once per worker thread (default: one worker per CPU core). Any state you construct inside the closure is created N times — yielding N completely independent copies. This is silent and compiles perfectly: there's no error, just N separate caches, N separate in-memory counters, or N separate connection pools that never coordinate.

rust
// WRONG — a fresh Vec is created for each of the N workers
// Every worker has its own isolated list; requests are distributed
// across workers, so the list appears empty or inconsistent
HttpServer::new(|| {
let state = web::Data::new(Mutex::new(Vec::<String>::new())); // N copies!
App::new()
.app_data(state)
.route("/items", web::get().to(list_items))
})
// RIGHT — construct state OUTSIDE the closure, clone the Arc in
let state = web::Data::new(Mutex::new(Vec::<String>::new())); // one Arc
HttpServer::new(move || {
App::new()
.app_data(state.clone()) // clone the Arc, not the data
.route("/items", web::get().to(list_items))
})
.workers(4)
.bind("0.0.0.0:8080")?
.run()
.await

The same rule applies to DB pools, Redis connections, caches, and any other shared resource. Build them once, outside HttpServer::new, wrap in web::Data::new (which is Arc), and .clone() the Data handle into each App factory invocation.

AI almost always builds state inside the closure because that's where all the App configuration lives — it looks natural. The bug only surfaces at runtime when you notice your in-memory state is silently partitioned.

2. web::Data<T> is an Arc — clone the handle, not the data

web::Data<T> is a newtype wrapper around Arc<T>. Cloning a web::Data<T> clones the Arc (cheap reference count bump) — the underlying T is shared. This is correct and expected:

rust
// In the factory:
.app_data(pool.clone()) // clones the Arc wrapper, not the pool
// In a handler:
async fn get_user(pool: web::Data<PgPool>, path: web::Path<u64>) -> impl Responder {
// pool.get_ref() gives &PgPool, or use Deref coercion
let row = sqlx::query!("SELECT * FROM users WHERE id = $1", *path)
.fetch_one(pool.get_ref())
.await;
...
}

`.data()` was removed in Actix-web 4. Use .app_data(web::Data::new(...)). It only appears in 3.x codebases and in training data from that era; code using it does not compile against 4.x at all.

Use `web::ThinData<T>` (added in 4.9.0) for state that is already cheap to clone. web::Data<T> wraps T in an Arc. When T is a PgPool, a redis::Client, or anything that is itself an Arc internally, web::Data gives you Arc<Arc<..>> — a second pointer chase on every extraction for no benefit. ThinData stores the value directly:

rust
// PgPool is already internally reference-counted — ThinData avoids the extra Arc
.app_data(web::ThinData(pool.clone()))
async fn get_user(web::ThinData(pool): web::ThinData<PgPool>) -> impl Responder { ... }

Keep web::Data for large or non-Clone values, and for anything you need to reach through HttpRequest::app_data. The construct-outside-the-closure rule in §1 applies to both.

3. Workers are single-threaded actix-rt — !Send types allowed, but blocking still starves the worker

Each Actix-web worker runs its own single-threaded actix-rt executor (a single-threaded Tokio runtime). Because the executor is single-threaded, handler futures do not need to be Send — you can use Rc<T>, Cell<T>, and other !Send types freely inside handlers. This is a deliberate design difference from Axum (which requires Send futures for multi-thread Tokio).

However: a single-threaded executor means blocking work blocks the entire worker thread, stalling all requests routed to that worker. The mir-backend-rust rule (don't block async tasks) applies here too, with one Actix-specific escape hatch:

  • For blocking/CPU-heavy work inside an Actix handler, use `web::block` — it runs the closure on a separate blocking threadpool and returns a Future:
rust
async fn compress_data(body: web::Bytes) -> actix_web::Result<web::Bytes> {
let compressed = web::block(move || {
// runs on blocking pool — won't stall the actix worker
compress_sync(&body)
})
.await
.map_err(|e| actix_web::error::ErrorInternalServerError(e))??;
Ok(compressed)
}

Do not use tokio::task::spawn_blocking in Actix handlers — it works, but web::block is the idiomatic Actix-web API and integrates with the error model. std::thread::sleep and sync I/O inside handlers are still blocked.

The absent `Send` bound removes a compiler safety net. On Axum, holding a std::sync::MutexGuard across an .await is a compile error because handler futures must be Send. On Actix it compiles, because they need not be. The same code that fails to build on Axum builds here and deadlocks the worker at runtime — and since one worker serves a share of all traffic, that is a partial outage, not one bad request. mir-backend-rust §2 has the full table. Review Actix handlers for guard-across-await by hand; nothing will flag it for you.

Two more consequences of the single-threaded worker model:

  • Worker count is fixed at startup (HttpServer::workers(n), default one per CPU core) and connections are assigned to workers as they arrive. One worker stuck on blocking work does not shed its already-accepted connections to the others.
  • `web::block` submits to a shared blocking pool, not to the worker. It is bounded — unbounded fan-out through it queues silently. The mir-backend-rust note on spawn_blocking thread-pool exhaustion applies to web::block too.
4. Extractor configuration — know the real defaults, and register the config in the right place

Actix-web extractors (Json<T>, Form<T>, Query<T>, Path<T>, Payload) are configured via typed config objects registered with .app_data(). There are defaults, and they are not "unlimited" — verified in the 4.x source:

ExtractorConfig typeDefault limit
web::Json<T>JsonConfig2 MB (2_097_152)
web::Form<T>FormConfig16 KB
web::Bytes / StringPayloadConfig256 KB (262_144)
web::Payload (raw stream)noneUnlimited. impl FromRequest for Payload just hands you the stream — PayloadConfig is never consulted. Use Payload::to_bytes_limited(n) or count bytes yourself
MultipartMultipartFormConfig (from actix-multipart)set it yourself — the total and per-field limits are what matter

So for Json/Form/Bytes/String the risk is not "AI forgot the limit and the body is unbounded." The two real failures are:

  1. The default is wrong for the route. 2 MB of JSON is a lot to parse per request on an endpoint that expects 2 KB. Lower it per scope. Conversely, an upload endpoint that legitimately needs 20 MB fails at 2 MB with a confusing error until someone raises it globally — raising it globally then applies to every JSON route in the app.
  2. The config is registered where it does not apply. .app_data(JsonConfig...) is resolved by type at extraction time from the nearest matching scope. Registered on the wrong App or Scope, it is silently ignored and the default applies. There is no warning.
rust
// Tighten per scope, not globally
let strict_json = web::JsonConfig::default()
.limit(16_384) // 16 KB — this endpoint takes a small object
.content_type_required(true)
.error_handler(|err, _req| {
// default rejections echo parse detail; return a fixed message instead
let response = HttpResponse::BadRequest().json(json!({ "error": "invalid JSON body" }));
actix_web::error::InternalError::from_response(err, response).into()
});
App::new()
.service(
web::scope("/api/v1/notes")
.app_data(strict_json.clone()) // applies to this scope only
.route("", web::post().to(create_note)),
)

QueryConfig, PathConfig and FormConfig take the same .error_handler. Use it: the default rejection body is Actix's plain-text parse error, which names your fields and types.

5. Route::wrap() must come after .to() — it used to fail silently

Route-level middleware is attached with Route::wrap(). .to() and .service() replace the route's service, so calling either one after .wrap() throws the wrapped service away. On Actix-web ≤ 4.13 that was silent: the middleware was dropped with no error. When that middleware is an auth guard, the route ships unauthenticated and nothing tells you.

rust
// WRONG — .to() after .wrap() replaces the wrapped service.
// <= 4.13: auth wrapper silently discarded, route is public. 4.14+: panics at startup.
web::resource("/admin").route(web::get().wrap(RequireAdmin).to(admin_handler));
// RIGHT — handler first, then wrap
web::resource("/admin").route(web::get().to(admin_handler).wrap(RequireAdmin));

Actix-web 4.14.0 turned this into a panic so the mistake is now loud at startup; the panic text spells out the fix (web::get().to(handler).wrap(mw)). That is a strong reason to be on 4.14.1: if you are on 4.13 or earlier, this bug is silent, and an audit of every .wrap() call site is the only way to find it. Write an integration test that asserts a protected route returns 401 without credentials — a test is the only thing that catches middleware that is present in the source but absent at runtime.

For new middleware prefer middleware::from_fn() (added in 4.9.0) over hand-implementing Transform + Service; the trait pair is where most custom Actix middleware bugs live.

6. Error handling — implement ResponseError, not unwrap

Actix-web's error trait is ResponseError (not IntoResponse as in Axum). Implement it on your error type to produce consistent HTTP responses:

rust
#[derive(Debug, thiserror::Error)]
enum AppError {
#[error("not found: {0}")]
NotFound(String),
#[error("database error")]
DbError(#[from] sqlx::Error),
#[error("unauthorized")]
Unauthorized,
}
impl ResponseError for AppError {
fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound(_) => StatusCode::NOT_FOUND,
AppError::DbError(_) => StatusCode::INTERNAL_SERVER_ERROR,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
}
}

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
15
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-rust-actix/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-rust-actix)

Something wrong with this skill or its page? Tell us.