Coding Standard: Rust

By Engineering Team•September 27, 2026•6 min read

Rust is used wherever a service’s core responsibility is handling encrypted secret material or gateway-facing token/App-Check verification on the hot path — see ADR-00010 for why. This doc is the concrete rulebook a Rust service is actually held to; Architecture-00007 covers the same shape across all three backend languages side by side.

Services on this standard

user-secure-engine, pii-service, pci-service, media-access-service, payment-service, document-service, provider-auth-service, notification-service.

Folder layout — feature first, layer second

domain/<feature>.rs               ← pure business types, one file per aggregate
domain/<feature>_validation.rs    ← validation — always its own file
repository/<feature>/             ← entity + mapper + trait + implementation
service/<feature>/                ← trait + implementation
transport/api/<feature>/          ← Axum controller + api-model + mapper
transport/grpc/<feature>/         ← Tonic server + DTO mapper
message_publisher/<event>.rs      ← flat file per event type
message_receiver/<event>.rs

No shared bootstrap exists across services — each hand-writes app_config.rs::start() (config → telemetry → DB → modules → serve), template-copied rather than framework-provided.

Error handling

Never hand-roll an error type. Use the error module’s AppError enum + AppResult<T> from rust-lang-core-lib — it implements IntoResponse directly, so a handler can return AppResult<T> and have HTTP/gRPC status mapping happen automatically (grpc::error maps AppError → tonic::Status).

The domain object (DTO) parameter pattern

One domain object per service-method call, never several positional scalars — identical rule to Go and Node, applied at every layer boundary (transport → service, service → repository).

Validation — its own file, always

domain/<feature>_validation.rs is separate from domain/<feature>.rs — never inline.

#[tracing::instrument] — mandatory on every public service and repository method

This is Rust’s equivalent of Go’s otel.WithSpan. Always skip() struct/reference parameters — never let them auto-print their Debug representation. Extract only the fields you actually need via fields(...).

// WRONG — logs "claims": "AuthClaims { user_id: ..., tenant_id: ... }" (verbose)
#[tracing::instrument(skip(self, repo), fields(tenant_id = %claims.tenant_id))]
async fn create(&self, input: Input, claims: &AuthClaims, repo: &dyn Trait) { ... }

// CORRECT — logs only the specific fields
#[tracing::instrument(skip(self, repo, claims), fields(tenant_id = %claims.tenant_id, user_id = %claims.user_id))]
async fn create(&self, input: Input, claims: &AuthClaims, repo: &dyn Trait) { ... }

Rule: every parameter that is a struct, reference to a struct, or trait object goes in skip(). Simple scalars (&str, Uuid) may stay in auto-capture or move to fields(). skip(self) avoids leaking secrets; skip(body) avoids logging request bodies (PII risk).

Logging macros

  • log_info! at entry and exit of every public service and repository method.
  • log_debug! for internal state useful during debugging.
  • log_error! before returning any AppError::Internal.
  • Never println!/eprintln!.
  • A value standing in for real secret material with no real provider behind it yet (e.g. a placeholder OTP) is log_debug!-only, never log_info!, so it’s structurally absent from production (LOG_LEVEL=info) logs.

Postgres pool tuning — automatic, zero call-site changes

db::connect_postgres(database_url) builds a sea_orm::ConnectOptions instead of a bare URL — every caller gets max_connections from env DB_MAX_CONNECTIONS (default 5), min_connections fixed at 1, idle_timeout fixed at 300s. Never bypass this by calling sea_orm::Database::connect directly with a raw URL string.

db::connect_mongo(uri, username, password, database, environment) keeps URI/username/password as always-separate config values, never a pre-baked connection string with embedded credentials; direct_connection is forced when environment is "development"/"local".

Entity/mapper split

repository/<feature>/ splits into entity + mapper + trait + implementation by default. A genuinely 1:1 shape may collapse the mapper into the entity file only when that template’s own CLAUDE.md says so explicitly.

The EAV pattern — shared implementation, per-service ownership boundary

pii-service and pci-service share one encryption-at-rest Entity-Attribute-Value implementation via rust-lang-core-lib’s domain::encrypt/service::encrypt/repository::encrypt modules, rather than two hand-maintained copies:

Owned by core-lib Owned by each service
domain::encrypt input/output types + validation Concrete SeaORM entity + repository impl — table_name/schema_name are compile-time macro attributes
service::encrypt::RowAttributeService — validates, encrypts/decrypts via AesGcmCipher, calls the repo, writes one AuditLogEntry per call The composition root wiring the above together per service
repository::encrypt traits + DTOs The gRPC handler mapping proto messages to/from the shared input types

The test: anything that must be a compile-time constant or a concrete wiring decision for one service stays local; everything expressible as generic input/output types and orchestration logic moves to the core lib.

External API integrations

A third-party HTTP API is wrapped behind repository/<provider>/ exactly like a database dependency — service/ never holds a raw reqwest::Client. payment-service’s repository/razorpay/ (razorpay_entity.rs, razorpay_rep.rs trait, razorpay_rep_impl.rs, composed via a build(cfg) -> Arc<dyn Trait> factory) is the reference. One method per provider endpoint — the RazorpayRepositoryTrait doc-comment explicitly instructs future contributors to add a method per new endpoint, never grow an existing one’s scope.

No over-engineering

No extra abstractions, error handling, or features beyond what the task requires. Validate only at system boundaries.

Comments

No comments unless the WHY is genuinely non-obvious.