Build a Production FastAPI Backend with Bolt.new
I built a production FastAPI backend with Bolt.new last quarter for a client who needed to move fast without hiring a full backend team. The generated code got them to a working API in hours instead of weeks but it fell apart under real traffic because Bolt optimizes for “it runs” not “it survives.” This post walks through the exact gaps I had to close to ship something that stays up at 3 AM.
What does Bolt.new actually generate for a FastAPI backend?
Bolt.new scaffolds a standard FastAPI project structure with routers, models, and a basic database setup. It creates a main.py with an app instance, a database.py using SQLAlchemy, and usually a requirements.txt pinned to recent versions. The code runs locally with uvicorn main:app --reload and you get Swagger docs at /docs out of the box. What it does not give you is connection pooling, migration tooling, structured logging, health checks, or any concept of environments. I treat the output as a first draft that compiles not a foundation.
How do I configure async SQLAlchemy and PostgreSQL for production?
The generated database.py typically uses create_engine with a synchronous driver. That blocks the event loop under load. Swap it for create_async_engine with asyncpg and use AsyncSession throughout. Here is the pattern I use in every production service:
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmakerfrom sqlalchemy.orm import DeclarativeBaseimport os
DATABASE_URL = os.getenv("DATABASE_URL") # postgresql+asyncpg://user:pass@host/db
engine = create_async_engine( DATABASE_URL, pool_size=10, max_overflow=20, pool_pre_ping=True, pool_recycle=300, echo=False,)
AsyncSessionLocal = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False)
class Base(DeclarativeBase): pass
async def get_db(): async with AsyncSessionLocal() as session: try: yield session finally: await session.close()Set pool_pre_ping=True so stale connections get validated before use. Set pool_recycle to stay under your cloud SQL proxy timeout. Run migrations with Alembic not Base.metadata.create_all. I wrote a deeper walkthrough of this pattern in FastAPI Async Lifespan: Startup, Shutdown & Cleanup Patterns because the lifespan hook is where you initialize the engine and close it on shutdown.
How do I add authentication and authorization with JWT?
Bolt often stubs a get_current_user dependency that reads a header and returns a hardcoded user. Replace it with a proper JWT flow using python-jose and passlib[bcrypt]. Store the secret in Secret Manager not a .env file. Issue short lived access tokens (15 minutes) and long lived refresh tokens (7 days) rotated on use. Keep the token payload small: user id, role, and expiry. Validate the signature and expiry in a single dependency:
from fastapi import Depends, HTTPException, statusfrom fastapi.security import OAuth2PasswordBearerfrom jose import JWTError, jwtfrom sqlalchemy.ext.asyncio import AsyncSessionfrom datetime import datetime, timedelta
SECRET_KEY = os.getenv("JWT_SECRET")ALGORITHM = "HS256"oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
async def get_current_user( token: str = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id: str = payload.get("sub") if user_id is None: raise credentials_exception except JWTError: raise credentials_exception
user = await db.get(User, user_id) if user is None: raise credentials_exception return userAdd role based checks with a simple dependency factory. Do not roll your own crypto. Do not put permissions in the token if they change frequently; hit the database instead.
What does a production Dockerfile look like for FastAPI?
The generated Dockerfile usually runs pip install -r requirements.txt in a single stage and starts with uvicorn main:app --host 0.0.0.0 --port 8000. That image is large, rebuilds slowly, and runs as root. Use a multi stage build with a slim base, install dependencies in a builder stage, copy only the wheels to the final stage, and run as a non root user. Here is the template I copy into every repo:
FROM python:3.12-slim AS builderWORKDIR /appRUN pip install --no-cache-dir --upgrade pip setuptools wheelCOPY requirements.txt .RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
FROM python:3.12-slim AS runtimeWORKDIR /appRUN addgroup --system appgroup && adduser --system --ingroup appgroup appuserCOPY --from=builder /wheels /wheelsRUN pip install --no-cache-dir --no-index --find-links /wheels /wheels/*COPY --chown=appuser:appgroup . .USER appuserENV PYTHONUNBUFFERED=1EXPOSE 8080CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "4"]Cloud Run expects port 8080. The --workers flag lets you use multiple CPU cores. I pin the Python version in both stages to avoid surprise rebuilds. If you want the full CI/CD wiring for this image, see GitHub Actions vs Cloud Build for Cloud Run CI/CD.
How do I deploy to Cloud Run with CI/CD?
Push the image to Artifact Registry, then deploy with gcloud run deploy. The pipeline should run tests, build the image, scan for vulnerabilities, and promote to staging then production on tag push. A minimal GitHub Actions workflow looks like this:
name: Deploy to Cloud Runon: push: tags: ["v*"]jobs: build-and-deploy: runs-on: ubuntu-latest permissions: contents: read id-token: write steps: - uses: actions/checkout@v4 - id: auth uses: google-github-actions/auth@v2 with: workload_identity_provider: ${{ secrets.WIF_PROVIDER }} service_account: ${{ secrets.SERVICE_ACCOUNT }} - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Build and push uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ secrets.ARTIFACT_REGISTRY }}/${{ github.repository }}:${{ github.ref_name }} cache-from: type=gha cache-to: type=gha,mode=max - name: Deploy to Cloud Run run: | gcloud run deploy ${{ github.repository }} \ --image ${{ secrets.ARTIFACT_REGISTRY }}/${{ github.repository }}:${{ github.ref_name }} \ --region us-central1 \ --platform managed \ --allow-unauthenticated \ --set-env-vars="DATABASE_URL=${{ secrets.DATABASE_URL }},JWT_SECRET=${{ secrets.JWT_SECRET }}"Use Workload Identity Federation instead of service account keys. Store secrets in Secret Manager and reference them at deploy time. The --allow-unauthenticated flag is fine for public APIs; remove it for internal services and enforce IAM.
How do I monitor and debug Bolt-generated code in production?
You cannot debug what you cannot see. Add structured JSON logging from day one. Use structlog with a processor that adds timestamp, level, service, and trace_id. Wire the trace ID from the X-Cloud-Trace-Context header so logs correlate in Cloud Logging. Expose a /healthz endpoint that checks database connectivity and returns 200 only if the pool can acquire a connection. Add Prometheus metrics with prometheus-fastapi-instrumentator and scrape them with Cloud Monitoring or a managed Grafana. Set up alerts for 5xx rate, latency p99, and connection pool exhaustion. I have been bitten by silent connection leaks that only showed up as “too many connections” errors at 2 AM. The fix was adding pool_pre_ping and a middleware that logs slow queries.
When should you not use Bolt.new for the backend?
Bolt is great for scaffolding CRUD APIs, internal tools, and prototypes where the schema is stable and the team knows FastAPI well enough to fix the gaps. It struggles with complex domain logic, event driven architectures, websocket heavy services, and anything that needs careful transaction boundaries. If your team cannot read the generated code and spot the missing await or the N+1 query, you will ship bugs. In those cases, write the skeleton yourself or hire someone who can. I help teams do exactly that at /hire/.
FAQ
Can Bolt.new generate a complete production backend?
No. Bolt generates a working prototype. You must add connection pooling, migrations, authentication, structured logging, health checks, multi stage Docker builds, and CI/CD yourself.
What is the biggest risk of deploying Bolt-generated FastAPI code?
The biggest risk is synchronous database calls blocking the event loop. Bolt often uses create_engine instead of create_async_engine which causes request latency to spike under concurrent load.
Do I need Alembic if I use SQLAlchemy models?
Yes. Base.metadata.create_all does not handle schema changes. Alembic gives you versioned, reviewable migrations that run safely in CI/CD.
How many workers should I run in Cloud Run?
Start with --workers 4 on a 2 CPU instance. Tune based on CPU utilization and request latency. Cloud Run charges for CPU only while handling requests so idle workers cost nothing.
Key Takeaways
- Treat Bolt.new output as a scaffold not a production foundation
- Use async SQLAlchemy with
asyncpgand connection pooling from day one - Implement JWT auth with short lived access tokens and rotated refresh tokens
- Build multi stage Docker images that run as non root on port 8080
- Deploy with Workload Identity Federation and Secret Manager references
- Add structured logging, health checks, and Prometheus metrics before launch
- If you cannot read the generated code and spot the gaps, do not ship it
Working on something similar?
If you're building backend or AI systems and want a second set of senior eyes, let's talk.