Back to Blog
System DesignPostgreSQLFastAPIScalabilityInfrastructure

Proactive Scaling: Designing Signale's Architecture for 1,000 Concurrent Users

Scaling backend APIs for high concurrency: A deep dive into connection pooling, sidecar patterns, and the nuance of prepared statements in Python.

Most engineering teams discover database connection exhaustion under production load when a traffic spike takes down their primary instance.

When architecting Signale (a multi-modal WhatsApp assistant), we designed for burst concurrency from day one. WhatsApp traffic is inherently spiky: a single forward in a large group chat or a scheduled reminder batch can trigger hundreds of concurrent webhook requests within seconds.

While FastAPI handles high asynchronous request concurrency in Python, pairing an async web tier directly with PostgreSQL creates an immediate bottleneck at the connection layer.

This post details how we configured transaction-mode connection multiplexing with PgBouncer and SQLAlchemy (asyncpg) to serve over 1,000 concurrent beta users without a single database connection timeout.

The Async-to-Postgres Connection Bottleneck

The bottleneck comes down to how each layer manages concurrency:

  1. FastAPI (asyncio / uvloop) is event-driven. A single container worker can hold thousands of concurrent coroutine requests open with minimal memory overhead while awaiting I/O.
  2. PostgreSQL uses a process-per-connection model. Every active client connection forks a dedicated OS backend process consuming roughly 10MB of RAM plus file descriptors.

If three FastAPI containers each open 150 connections during a webhook burst, PostgreSQL is forced to allocate 450 backend processes—exhausting max_connections and thrashing CPU on OS context switching rather than executing queries.

The Solution: PgBouncer in Transaction Mode

To decouple application concurrency from database process count, we deployed PgBouncer as a connection multiplexer between the FastAPI workers and PostgreSQL:

[FastAPI Replica 1] --(50)--> \
                               \
[FastAPI Replica 2] --(50)--> [ PgBouncer ] --(20)--> [(PostgreSQL)]
                               /
[FastAPI Replica 3] --(50)--> /

Instead of 150 client connections hitting PostgreSQL directly, PgBouncer maintains a fixed pool of 20 physical database connections. Incoming queries borrow a backend connection only for the duration of a single SQL transaction, then release it immediately back to the pool while libevent queues waiting coroutines with negligible memory overhead.

Resolving the asyncpg Prepared Statement Conflict

Dropping PgBouncer in front of a modern Python asyncpg application in Transaction Mode (pool_mode = transaction) immediately triggers a protocol conflict if left at default settings.

By default, asyncpg optimizes repeated queries by creating session-scoped Prepared Statements on the PostgreSQL backend connection (PREPARE stmt_1 AS ...) and caching the statement handle in memory.

In transaction pooling mode, consecutive queries from the same FastAPI client session are multiplexed across different physical PostgreSQL connections. When asyncpg attempts to execute stmt_1 on a subsequent transaction, PgBouncer routes the request to a backend connection where stmt_1 was never prepared, raising:

asyncpg.exceptions.InvalidSQLStatementNameError: prepared statement "__asyncpg_stmt_1__" does not exist

Disabling Driver-Level Statement Caching

To make SQLAlchemy's async engine compatible with PgBouncer transaction multiplexing, both SQLAlchemy's internal statement cache and asyncpg's protocol-level prepared statement cache must be explicitly disabled:

# app/database/session.py
 
engine = create_async_engine(
    settings.DATABASE_URL,
    pool_size=20,
    max_overflow=10,
    connect_args={
        # Required for PgBouncer pool_mode=transaction compatibility
        "prepared_statement_cache_size": 0,
        "statement_cache_size": 0,
    },
)

Trading away a few microseconds of query plan reuse on simple CRUD lookups allows thousands of concurrent application coroutines to share 20 physical database connections safely.

Production Telemetry Under Launch Load

When Signale opened its public beta, webhook bursts matched our load-test profile:

  • Peak Concurrent Users: ~1,200
  • FastAPI p95 Latency: ~120ms
  • Database CPU Utilization: < 15%
  • Active PostgreSQL Backend Connections: Capped cleanly at 20

By aligning asyncpg protocol behavior with PgBouncer transaction pooling before launch, traffic spikes were absorbed entirely at the stateless multiplexing layer without scaling up the underlying database instance.

— Pedro

Founder & Principal Engineer