rust-architecture
Skill1 starsChanged 41 days agoMITView on GitHub
Hexagonal architecture (ports and adapters) in Rust — a domain core that depends on nothing, ports as traits, adapters at the edges, one-way dependency flow toward the domain. Use when structuring an app/service, isolating business logic from frameworks, deciding module layout, or making code testable without infrastructure. Triggers: ports and adapters, clean architecture, dependency inversion, repository pattern, where does this code go.
2 other projects use a version of this.
Adopted by
Most recently taken up by
- JSBtechnologies/rustkbtheir own version, first seen Oct 11, 2026
- dawidpereira/rust-skillstheir own version, first seen Mar 22, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- dawidpereira/rust-skills★ 0same name
- JSBtechnologies/rustkb★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository42 other files it gives its agents.
- AGENTS.mdAGENTS.md
- addressing-findingsSkill
- auditSkill
- codebase-onboardingSkill
- codex-reviewSkill
- compatibilitySkill
- debuggingSkill
- developSkill
- distributed-racesSkill
- memorySkill
- nix-dev-envSkill
- nix-flakesSkill
- nixosSkill
- nix-packagingSkill
- nix-reviewSkill
- refactoringSkill
- retroSkill
- review-initSkill
- review-rulesSkill
- rust-architecture-reviewSkill
- rust-cliSkill
- rust-cloud-nativeSkill
- rust-concurrencySkill
- rust-ecosystemSkill
- rust-embeddedSkill
- rust-errorsSkill
- rust-fintechSkill
- rust-idiomsSkill
- rust-macrosSkill
- rust-mlSkill
- rust-navigationSkill
- rust-ownershipSkill
- rust-performanceSkill
- rust-pluginsSkill
- rust-reviewSkill
- rust-securitySkill
- rust-testingSkill
- rust-traitsSkill
- rust-unsafeSkill
- rust-webSkill
- specsSkill
- sql-reviewSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 2 are distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 21
When not to: a tiny CLI or script doesn't need ports — the indirection costs more than it saves.
- Distinctive: line 23
Read Criticism below before adopting it wholesale — this pattern is frequently over-applied.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Rust Architecture — Hexagonal (Ports & Adapters)
One rule drives everything: dependencies point only toward the domain. Business logic sits at the center knowing nothing about HTTP, SQL, or any framework; the outside world plugs in through traits (ports) implemented at the edges (adapters). The Rust mechanics — ports as traits, the service struct, error translation — are in the sub-files.
When to Use
- Structuring a service/application beyond a single file
- Keeping business logic independent of axum/sqlx/etc. so frameworks can change
- Making logic testable without a database or network
- Deciding "where does this code go?"
When not to: a tiny CLI or script doesn't need ports — the indirection costs more than it saves. Reach for this when the app has real business rules and more than one external dependency. Read Criticism below before adopting it wholesale — this pattern is frequently over-applied.
Criticism — when to keep it simple
The Rust community pushes back hard on cargo-culting this pattern (HN/Lobsters/Reddit on the guide that inspired this skill). Take the critiques seriously:
- Don't abstract before you have 2–3 real implementations. A port (trait) with a single implementor is pure indirection — "hell is full of single-implementation abstractions." Start with concrete types; extract a port when a second adapter actually appears.
- The "where tf" problem. Layers scatter logic; to follow control flow you hop through traits to find the one impl. Indirection has a real readability cost — pay it only for real flexibility.
- Generics everywhere fight the language.
Service<R, M, N>andClone + Send + Sync + 'staticbounds propagate, collide with lifetimes, and push you towardArc/Mutex— losing the stack allocation and borrowing that make Rust fast.async fnin traits needs the-> impl Future + Senddesugar ortrait-variant; that tax is real. - The swap rarely happens. "We might switch databases" almost never materializes, and when it does the semantic differences dwarf the abstraction's help.
Pragmatic middle grounds many prefer:
- Functional core, imperative shell — pure logic over plain data in the center, side effects at the edges; often gets you testability without a web of traits.
- Colocated trait-based injection —
repo.upsert(&conn).await?keeps logic readable without a full ports layer. - Integration tests over mocks —
testcontainersor a real local DB exercises the actual adapter; mocking the database can test your mock instead of your code.
Rule: start concrete, introduce ports when a real second implementation or a genuine testing seam demands one. Use the full structure below for apps that have earned it — not by default.
The three layers
inbound adapters outbound adapters
(HTTP handler, CLI, gRPC) (sqlx repo, email, metrics)
│ call ▲ implement
▼ │
┌───────────────────────────── DOMAIN ─────────────────────────────┐
│ models (validated) inbound ports (traits) outbound ports (traits)│
│ Service: implements inbound ports, orchestrates outbound ports │
│ domain errors — depends on NOTHING external — │
└──────────────────────────────────────────────────────────────────────┘- Domain / core — models, ports, errors, and the
Service. No framework types here, ever. - Ports — traits the domain owns. Inbound (driving): how the world calls the domain
(e.g.
AuthorService). Outbound (driven): what the domain needs from the world (AuthorRepository,Notifier,Metrics). Details: ports.md. - Adapters — concrete impls at the edges. Inbound: an axum handler that translates an
HTTP DTO into a domain call. Outbound: a
Sqlitestruct wrappingsqlxthat implementsAuthorRepository. Details: adapters.md.
The dependency rule
Adapters depend on the domain; the domain never depends on an adapter. Because the domain
defines the ports and adapters implement them, the compile-time dependency arrow is inverted —
this is dependency inversion, enforced by the module graph. If domain/ uses anything from
outbound/ or a framework crate, the architecture is already broken.
Wiring: main is the only place that knows everything
The domain is generic over its ports; main picks concrete adapters and assembles them:
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let repo = Sqlite::new(&cfg.database_url).await?; // outbound adapter
let metrics = Prometheus::new(); // outbound adapter
let notifier = EmailNotifier::new(&cfg.smtp); // outbound adapter
let service = Service::new(repo, metrics, notifier); // domain, wired (all three ports)
let server = HttpServer::new(service).await?; // inbound adapter
server.run().await
}main is bootstrapping only — no business logic.
Generics vs dyn for wiring
Wire ports with generics by default — Service<R: AuthorRepository> — for static dispatch
and zero overhead. Use Arc<dyn AuthorRepository> only when you genuinely need runtime
polymorphism or the set of impls isn't known at compile time. (The full static/dyn/enum
trade-off is in rust-traits → dispatch.)
Note: the generic port as written in ports.md is not dyn-compatible, so
Arc<dyn AuthorRepository> won't compile against it unchanged. Two things block a vtable: the
Clone supertrait is Sized (a dyn value has no statically known size), and the RPITIT
-> impl Future has no single vtable-able return type. To use dyn, the port must drop the
Clone bound, box the future (async-trait, or a hand-written -> Pin<Box<dyn Future + Send>>),
and recover cheap cloning by wrapping the trait object in Arc (clone the Arc, not the impl).
See rust-traits → dispatch for the full dyn-compatibility constraints.
Module layout
src/
├── domain/
│ └── author/
│ ├── models.rs # Author, CreateAuthorRequest (validated constructors)
│ ├── ports.rs # AuthorService (inbound), AuthorRepository/Metrics (outbound)
│ ├── errors.rs # CreateAuthorError
│ └── service.rs # Service<R, M, ...> implementing the inbound port
├── inbound/
│ └── http/ # axum handlers + HTTP DTOs ⇄ domain
├── outbound/
│ ├── sqlite.rs # AuthorRepository impl (wraps sqlx)
│ └── prometheus.rs # AuthorMetrics impl
└── main.rs # wiring onlyNames are yours to choose — keep the direction (inbound/domain/outbound) clear.
Boundaries
This skill owns the structure: layers, the dependency rule, ports as traits, the service, and adapter/error-translation seams. It deliberately does not cover the mechanics that other craft skills own — go there for the details:
- Dispatch (static/
dyn/enum), dyn-compatibility, newtype & typestate →rust-traits. Validated newtype models ("parse, don't validate") and the generics-vs-dynchoice live there. - Failures-vs-defects error design →
rust-errors. The catch-allUnknown(anyhow::Error)and the library-vs-app split are defined and justified there; this skill only applies them at the boundary. - axum handler/extractor mechanics (
State,Json, status codes, routing) →rust-web. Here we only show the translate-don't-compute shape of an inbound adapter. - Port mocks/fakes (
mockall#[automock], fake injection, integration tests) →rust-testing.
Cross-links for scaling up: separate read/write models and event-as-source-of-truth → cqrs-events.md (CQRS & event sourcing — with a "when not to" warning).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

