Skip to content
Back to blog
  • AWS
  • Engineering
  • DevOps

Rotating Secrets in AWS Secrets Manager FastAPI Services

Learn how to fetch, cache, and rotate database credentials dynamically in FastAPI using AWS Secrets Manager and SQLAlchemy without application downtime.

MMuhammad Muneeb4 min read

Injecting database credentials through environment variables at startup is common practice, but it breaks down the moment security mandates automatic credential rotation. When AWS Secrets Manager triggers a rotation lambda to update your database password, any running task holding stale environment variables begins throwing authentication errors until the orchestrator replaces the container. For high-availability services, building resilient AWS Secrets Manager FastAPI integration means refreshing database credentials on the fly without restarting pods or severing active connections.

Instead of treating environment configs as immutable state, production systems need dynamic credential management. Just like we avoid handling raw payloads directly when uploading files using S3 presigned URLs, offloading database credential lifecycles to AWS allows the application to remain decoupled from manual administrative tasks. The challenge lies in minimizing network latency while preventing authentication failures during scheduled rotations.

The Challenge with Static Secrets in Long-Running Tasks

In a standard containerized setup running on ECS or Kubernetes, the orchestrator pulls credentials once before spawning the ASGI server. If your organization enforces a 30-day rotation policy, Secrets Manager generates a new password and marks the old one for revocation. As soon as the database server drops support for the prior password, your SQLAlchemy or asyncpg connection pools fail their health checks.

You could trigger rolling restarts through CI/CD webhooks, but this introduces unnecessary deployment overhead, brief connection spikes, and risks during zero-downtime windows. A cleaner engineering approach handles FastAPI credential rotation internally: retrieve credentials lazily, keep them in memory with a short-lived cache, and catch authentication errors to trigger an immediate cache invalidation.

Implementing Boto3 Secret Caching with Thread Safety

Calling the AWS Secrets Manager API on every incoming HTTP request introduces severe performance bottlenecks and exhausts API rate limits. To make Python AWS Secrets Manager access production-ready, we combine boto3 with an in-memory TTL cache protected by a lock to ensure thread safety across concurrent workers.

Below is an implementation of a secret client that handles boto3 secret caching, background TTL management, and explicit cache invalidation when a rotation event occurs.

app/core/secrets.py
import json
import time
from threading import Lock
import boto3
from botocore.exceptions import ClientError

class SecretManager:
    def __init__(self, secret_name: str, region_name: str = "us-east-1", ttl_seconds: int = 300):
        self.secret_name = secret_name
        self.ttl_seconds = ttl_seconds
        self.client = boto3.client("secretsmanager", region_name=region_name)
        self._cached_secret = None
        self._last_fetched_at = 0
        self._lock = Lock()

    def get_secret(self, force_refresh: bool = False) -> dict:
        current_time = time.time()
        if not force_refresh and self._cached_secret and (current_time - self._last_fetched_at < self.ttl_seconds):
            return self._cached_secret

        with self._lock:
            # Double-check condition inside lock to avoid race conditions
            if not force_refresh and self._cached_secret and (time.time() - self._last_fetched_at < self.ttl_seconds):
                return self._cached_secret

            try:
                response = self.client.get_secret_value(SecretId=self.secret_name)
                secret_string = response.get("SecretString")
                if not secret_string:
                    raise ValueError(f"Secret {self.secret_name} has no SecretString.")

                self._cached_secret = json.loads(secret_string)
                self._last_fetched_at = time.time()
                return self._cached_secret
            except ClientError as exc:
                raise RuntimeError(f"Failed to retrieve secret from AWS: {exc}")

Integrating Dynamic Credentials with SQLAlchemy and Asyncpg

Now that we have a caching layer, the database engine must consume it dynamically. Standard SQLAlchemy engines use a static connection URL provided at boot time. However, modern database drivers allow passing a dynamic URL or injecting connection parameters during pool checkouts.

When building fault-tolerant backend services, handling authentication shifts mirrors the logic used for idempotent webhook retries: detect the specific error signature, refresh the state, and retry the operation once before failing permanently. For PostgreSQL databases, a stale password produces an invalid authorization specification error (SQLSTATE code 28P01).

We can leverage SQLAlchemy event hooks to provide updated connection arguments dynamically, or wrap session acquisition in an automatic recovery interceptor.

app/core/database.py
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import DBAPIError
from app.core.secrets import SecretManager

secret_manager = SecretManager(secret_name="production/rds/postgres")

def build_connection_url(creds: dict) -> str:
    user = creds["username"]
    password = creds["password"]
    host = creds["host"]
    port = creds.get("port", 5432)
    dbname = creds["dbname"]
    return f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{dbname}"

initial_creds = secret_manager.get_secret()
engine = create_async_engine(build_connection_url(initial_creds), pool_pre_ping=True)
async_session_factory = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
    global engine, async_session_factory
    session = async_session_factory()
    try:
        yield session
    except DBAPIError as exc:
        # Check if the failure is caused by authentication rejection
        if "28P01" in str(exc.orig) or "password authentication failed" in str(exc).lower():
            await session.close()
            # Force fetch the latest secret and re-bind engine
            updated_creds = secret_manager.get_secret(force_refresh=True)
            await engine.dispose()
            engine = create_async_engine(build_connection_url(updated_creds), pool_pre_ping=True)
            async_session_factory = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
            raise RuntimeError("Credentials rotated. Reconnect required.") from exc
        raise
    finally:
        await session.close()

Handling Rotation in AWS Secrets Manager FastAPI Endpoints

The final step is connecting the session dependency to your route handlers. In production, an AWS Lambda rotation task updates the password on RDS and registers it inside Secrets Manager. During the brief propagation period, active connections will finish their queries, but newly requested connections might fail against the stale engine pool.

By combining connection pre-pinging with our refresh interceptor, the first request encountering an expired password invalidates the cache, disposes of dead connections, and initializes the new engine. This pattern keeps the operational footprint small and mirrors the lean approach we take when designing scalable serverless APIs on AWS Lambda, ensuring the compute layer handles infrastructure changes gracefully without human intervention.

app/api/routes.py
from fastapi import FastAPI, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
from app.core.database import get_db_session

app = FastAPI(title="Resilient API")

@app.get("/health/db", status_code=status.HTTP_200_OK)
async def database_health_check(db: AsyncSession = Depends(get_db_session)):
    try:
        result = await db.execute(text("SELECT 1"))
        return {"status": "healthy", "result": result.scalar()}
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=f"Database connectivity check failed: {str(exc)}"
        )

Production Trade-offs and Best Practices

While dynamic rotation prevents service downtime, it introduces architectural trade-offs you must plan for:

  • Avoid multi-process race conditions: If running with multiple Gunicorn or Uvicorn workers, each process maintains its own memory space. Stagger rotation schedules or use an IPC channel if synchronous invalidation is required across child processes.
  • IAM least privilege: Ensure the task role has permissions restricted strictly to secretsmanager:GetSecretValue on the specific ARN, rather than wildcard secret access.
  • Keep cache TTLs balanced: A 5-minute TTL offers a solid balance between minimizing AWS API charges and avoiding prolonged reliance on stale cache values.
  • Set sensible connection pool recycle limits: Use pool_recycle in SQLAlchemy so connections naturally close and refresh before hitting RDS limits.

Treating infrastructure credentials as dynamic, ephemeral tokens rather than immutable boot variables leads to significantly more robust deployments. With an in-memory cache and a clean error recovery loop, your FastAPI applications can adapt to automated secret rotations without dropping customer traffic or demanding manual restarts.

Related posts