# Actix Web + PostgreSQL

> High-performance Rust web framework with PostgreSQL.

- Category: Full Web Stacks
- Difficulty: advanced
- Components: actix, postgres
- Tags: actix, rust, postgres, performance
- Source: https://docker.recipes/full-stacks/actix-postgres

## Overview

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust built on the Actor model. Originally created by Nikolay Kim in 2018, Actix Web has consistently ranked as one of the fastest web frameworks in any programming language, leveraging Rust's memory safety and zero-cost abstractions to deliver exceptional performance. The framework uses an actor-based architecture where each component operates as an independent actor, communicating through message passing, which naturally provides excellent concurrency and fault tolerance.

This stack combines Actix Web's blazing-fast HTTP handling capabilities with PostgreSQL's enterprise-grade database features, creating a high-performance backend solution optimized for demanding applications. Actix Web's async-first design pairs exceptionally well with PostgreSQL's robust connection pooling and transaction management, while libraries like SQLx provide compile-time checked queries that eliminate runtime SQL errors. The combination delivers both raw speed and data reliability, making it ideal for applications that cannot compromise on either performance or data integrity.

This configuration is perfect for Rust developers building production-grade APIs, financial technology platforms, IoT data collection systems, or any high-throughput application requiring guaranteed data consistency. Companies migrating from slower interpreted languages often choose this stack to achieve 10x+ performance improvements while maintaining PostgreSQL's proven reliability. The learning curve is steep due to Rust's ownership model, but the payoff includes memory safety, predictable performance, and significantly reduced infrastructure costs due to lower resource consumption.

## Features

- Actor-based concurrency model enabling millions of concurrent connections with minimal resource overhead
- Compile-time SQL query validation through SQLx preventing runtime database errors
- Zero-copy request parsing and response generation for maximum throughput
- Built-in middleware ecosystem including authentication, CORS, logging, and request compression
- PostgreSQL's JSONB support for hybrid relational-document data models with full indexing
- Advanced connection pooling with configurable pool sizes and connection lifecycle management
- Hot-reloading development server with automatic restart on code changes
- Native support for HTTP/2, WebSockets, and Server-Sent Events

## Use cases

- High-frequency trading platforms requiring microsecond response times with ACID transaction guarantees
- IoT data ingestion APIs handling millions of sensor readings per minute
- Financial services backends processing payment transactions with strict data consistency requirements
- Real-time multiplayer game servers with persistent player data and leaderboards
- E-commerce platforms managing inventory, orders, and user sessions under heavy load
- Analytics APIs serving complex queries over large datasets with PostgreSQL's window functions
- Cryptocurrency exchanges requiring ultra-low latency order matching and trade execution

## Prerequisites

- Rust development environment with Cargo package manager installed
- Minimum 2GB RAM (4GB+ recommended for PostgreSQL under load)
- Understanding of Rust ownership concepts and async/await programming model
- Familiarity with PostgreSQL schema design and query optimization
- Docker port 8080 available for Actix Web HTTP server
- Basic knowledge of Actor model patterns and message-driven architecture

## docker-compose.yml

```yaml
services:
  actix:
    build: .
    container_name: actix
    environment:
      DATABASE_URL: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
    ports:
      - "8080:8080"
    depends_on:
      - postgres
    networks:
      - actix-network

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: ${DB_NAME}
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - actix-network

volumes:
  postgres_data:

networks:
  actix-network:
    driver: bridge
```

## .env

```bash
DB_NAME=actix
DB_USER=actix
DB_PASSWORD=changeme
```

## Usage notes

- Docs: https://actix.rs/docs/
- Access at http://localhost:8080
- One of the fastest web frameworks (any language)
- Actor model for concurrency
- Use SQLx for async database access
- Multi-stage Dockerfile: build with rust, run with minimal image

## Troubleshooting

- Connection pool exhausted errors: Increase max_connections in PostgreSQL config and tune SQLx pool settings
- Cargo build failures with linking errors: Ensure PostgreSQL development headers are available in build container
- High memory usage during compilation: Use multi-stage Dockerfile with separate build and runtime images
- Database connection timeouts: Verify DATABASE_URL format and network connectivity between containers
- Actix runtime panics on heavy load: Tune worker thread counts and async task spawning limits
- SQLx migration failures: Check PostgreSQL user permissions and ensure database exists before running migrations

