A practical walkthrough of building medium-sized backend services in Rust with PostgreSQL, covering the HTTP stack (tokio, rustls, hyper, axum, reqwest, tower, tracing), a layered code organization (HTTP/service/repository), background jobs and cron leader election with Postgres advisory locks, caching guidance with moka, and serving SPAs directly from the API server to avoid CORS overhead.

10m read timeFrom kerkour.com
Post cover image
Table of contents
Rust's HTTP ecosystemCode organizationHTTP layerServicesRepositoriesBackground jobs (queue)Cron jobsCachingLoggingServing Single Page Applications and static assetsSome Closing Thoughts

Questions this post answers

What crates do I need to build an HTTP server in Rust with TLS support?

A typical Rust HTTP server stack layers tokio for async networking, a TLS crate like rustls (recommended over openssl or boring because it's statically linked and avoids OpenSSL version issues when deploying), tokio-rustls to bridge tokio streams with TLS, hyper to parse bytes into Request/Response structs, and axum on top for routing, middleware, and extractors. daily.dev surfaces practical breakdowns like this for developers piecing together a Rust HTTP stack.

How do you implement leader election for cron jobs running on multiple service replicas?

Leader election for cron jobs across multiple replicas can be implemented using PostgreSQL's advisory locks, where each replica attempts to acquire a named lock and only the one that succeeds runs the scheduler, preventing duplicate task execution across high-availability instances without needing a separate coordination service. Teams weighing coordination strategies for distributed schedulers can track patterns like this on daily.dev.

Should caching logic live in the repository layer or the service layer in a layered Rust backend?

Caching should live exclusively in the service layer, not the repository layer, because the repository layer should stay 'dumb' and only wrap database queries, while caching decisions (like how long an entity is safe to cache) depend on business rules that belong with the service logic. A general-purpose library like moka is sufficient for most cases. Developers structuring layered backend codebases can find architecture patterns like this on daily.dev.

16.6K Impressions3 Comments