All writing
bolt fastapi python backend

Bolt.new Python Backend: FastAPI from Zero to Production

Ayush Kaushik 9 min read
Bolt.new Python Backend: FastAPI from Zero to Production

If you need a bolt new python backend that’s up and running in minutes, you can get a FastAPI service with a single command and a sensible folder layout. It works for prototypes, but it also scales to production when you add async DB support, proper logging, and a CI pipeline. Below I’ll walk through exactly how I did it, the hiccups that tripped me up, and when you might want to stick with a hand-crafted FastAPI project instead.


What is Bolt.new and how does it simplify backend development?

Bolt.new is a CLI that generates a ready-to-run FastAPI skeleton. It chooses sensible defaults: Pydantic models for request validation, Uvicorn as the ASGI server, and a docker-compose.yml that spins up a PostgreSQL container. The generated code follows the “router-service-repository” pattern, so you can drop in business logic without fighting the structure.

The biggest win is the speed of scaffolding. Where a vanilla FastAPI project might take you an hour to set up routing, dependency injection, and a Dockerfile, Bolt.new does it in under a minute:

Terminal window
pip install bolt-new
bolt new myapp --framework fastapi
cd myapp
docker compose up -d
uvicorn app.main:app --reload

You get a working API at http://localhost:8000/health within seconds. That’s the answer to “how do I get a bolt new python backend running?” – run the CLI, and you have a functional service.


Step-by-step: scaffolding a FastAPI project with Bolt.new

  1. Install the CLIpip install bolt-new (requires Python 3.9+).
  2. Create the projectbolt new ai-service --framework fastapi.
  • The command creates ai_service/ with app/, tests/, Dockerfile, docker-compose.yml, and a pyproject.toml.
  1. Review the generated routerapp/api/v1/health.py contains:
from fastapi import APIRouter
router = APIRouter()
@router.get("/health")
async def health_check() -> dict:
return {"status": "ok"}
  1. Mount the routerapp/main.py already includes:
from fastapi import FastAPI
from .api.v1 import health
app = FastAPI(title="Bolt.new Demo")
app.include_router(health.router, prefix="/v1")
  1. Run locallydocker compose up -d starts PostgreSQL, then uvicorn app.main:app --reload.
  2. Testcurl http://localhost:8000/v1/health returns {"status":"ok"}.

That’s it. The scaffold gives you a clean entry point, a dev-ready Docker setup, and a test suite stubbed with pytest. If you need a quick AI endpoint, just drop a new router file under app/api/v1/ and import it in main.py.


Adding async database support (SQLAlchemy/Prisma) in a Bolt.new backend

Bolt.new ships with a synchronous SQLAlchemy example, but production workloads need async I/O. Here’s how I swapped in SQLModel (built on async SQLAlchemy) and why I considered Prisma as an alternative.

1. Install async dependencies

Terminal window
poetry add sqlmodel[async] asyncpg

2. Create the async engine

app/db.py

from sqlmodel import SQLModel, create_engine
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import AsyncEngine
DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost:5432/bolt_db"
engine: AsyncEngine = create_engine(DATABASE_URL, echo=False, future=True)
async def get_session() -> AsyncSession:
async with AsyncSession(engine) as session:
yield session

3. Define a model

app/models/item.py

from sqlmodel import Field, SQLModel
class Item(SQLModel, table=True):
id: int = Field(default=None, primary_key=True)
name: str
description: str | None = None

4. Add CRUD routes

app/api/v1/items.py

from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel.ext.asyncio.session import AsyncSession
from ..db import get_session
from ..models.item import Item
router = APIRouter(prefix="/items", tags=["items"])
@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item, session: AsyncSession = Depends(get_session)):
session.add(item)
await session.commit()
await session.refresh(item)
return item
@router.get("/{item_id}", response_model=Item)
async def read_item(item_id: int, session: AsyncSession = Depends(get_session)):
result = await session.get(Item, item_id)
if not result:
raise HTTPException(status_code=404, detail="Item not found")
return result

5. Register the router

In app/main.py add:

from .api.v1 import items
app.include_router(items.router, prefix="/v1")

6. Run migrations

Bolt.new doesn’t include Alembic out of the box, so I added:

Terminal window
poetry add alembic
alembic init alembic

Configure alembic/env.py to use the async engine and run alembic revision --autogenerate -m "create items" followed by alembic upgrade head.

Why not Prisma?

Prisma’s Python client is still experimental, and the generated async client adds another layer of code generation. For a solo builder who wants stability, async SQLAlchemy (or SQLModel) is the safer bet. If you already use Prisma in a Node service and love its type-safety, you can spin up a separate microservice and talk over HTTP, but that defeats the “single bolt new python backend” simplicity.


Deploying the Bolt.new FastAPI service to cloud platforms (Railway, Render, Fly.io)

Once the API works locally, the next question is “where do I host it without blowing the budget?” I’ve tried three cheap options. All of them accept a Docker image, so the Dockerfile generated by Bolt.new works unchanged.

Railway

  1. Connect the repo, enable “Dockerfile” detection.
  2. Set environment variable DATABASE_URL to the Railway-provided Postgres URL.
  3. Deploy – Railway builds the image, runs it, and gives you a public URL.

Gotchas: Railway’s free tier sleeps after 30 minutes of inactivity. If your AI endpoint is latency-sensitive, you’ll see a cold-start delay (2-3 seconds). The workaround is to add a tiny “keep-alive” cron that pings /health every 5 minutes.

Render

Render’s free web services also sleep, but you can upgrade to the “Starter” plan for $7/mo and get always-on containers. The platform automatically provisions a Postgres instance and injects DATABASE_URL. Deploy steps are identical to Railway.

Pitfall: Render expects the container to listen on the $PORT env var. The default Dockerfile from Bolt.new uses EXPOSE 8000. Change the entrypoint:

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "${PORT}"]

Fly.io

Fly.io is great for global latency. You define a fly.toml:

app = "bolt-fastapi"
kill_signal = "SIGINT"
kill_timeout = 5
[env]
DATABASE_URL = "postgres://..."
[[services]]
internal_port = 8000
protocol = "tcp"
[[services.ports]]
handlers = ["http"]
port = 80

Deploy with fly deploy. Fly keeps the container warm, so cold starts are rare.

Cost: The free tier gives you 3 GB-hours per month, enough for a low-traffic prototype. Once you exceed that, you pay $5/mo per 256 MB of RAM. For a single FastAPI instance, $5–$7/mo is typical.


Common pitfalls and performance tuning tips for production-grade Bolt.new apps

1. MissingGreenlet error

When I first added async SQLAlchemy, the app crashed with:

sqlalchemy.exc.MissingGreenletError: Greenlet is required for async support

The fix is to install greenlet explicitly:

Terminal window
poetry add greenlet

Bolt.new’s generated requirements.txt doesn’t include it because the default scaffold uses sync SQLAlchemy. Always double-check async dependencies.

2. Database connection pool exhaustion

FastAPI spawns many coroutines; each request can open a new DB connection if you’re not careful. In app/db.py set a pool size:

engine = create_engine(
DATABASE_URL,
pool_size=20,
max_overflow=10,
echo=False,
)

Monitor the pool with SELECT * FROM pg_stat_activity; on your Postgres instance.

3. Logging overhead

The default logger from Bolt.new prints every request line, which hurts performance under load. Switch to uvicorn[standard] and configure a JSON logger:

import logging
logging.basicConfig(level=logging.INFO, format='%(message)s')

Send logs to a service like Logtail or Papertrail for easier debugging.

4. Cold starts on serverless platforms

If you deploy to Cloud Run or a serverless variant of Railway, the first request after a period of inactivity can take 2–5 seconds. Mitigate by:

  • Keeping the container warm with a health-check ping.
  • Reducing the container size to 256 MiB (cold starts are faster on smaller images).
  • Pre-warming the model if you’re loading a large ML artifact; load it at import time, not per request.

5. Secret management

Never hard-code API keys in the repo. Bolt.new’s .env.example shows the pattern, but you must add the real values to the platform’s secret store. Missing a secret leads to a 500 error that’s hard to trace.


Bolt.new vs a traditional FastAPI setup: pros, cons, and cost considerations

AspectBolt.newHand-crafted FastAPI
Speed of initial setupSeconds with a CLIHours to configure Docker, linting, CI
Learning curveLow – opinionated defaultsHigher – you choose every library
FlexibilityModerate – you can replace parts, but the scaffold expects certain pathsUnlimited – you decide project layout
Production readinessGood for small-to-medium services; you still need to add logging, migrations, monitoringCan be built with enterprise-grade patterns from the start
CostFree CLI, same hosting costs as any Docker appSame hosting costs; no extra licensing
When to avoidYou need custom auth flow, complex event-driven architecture, or multi-service monorepoYou already have a mature CI/CD pipeline and want full control

In practice, I start with Bolt.new for a new AI microservice because it lets me ship a prototype in a day. When the traffic grows beyond a few hundred RPS, I audit the generated code, replace the router with a more modular approach, and add OpenTelemetry. The transition is painless because the scaffold follows standard FastAPI conventions.


FAQ

How do I add CORS support to a bolt new python backend?
Add from fastapi.middleware.cors import CORSMiddleware in app/main.py and configure:

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

Can I use Bolt.new with a non-Postgres database?
Yes. Change DATABASE_URL in the .env file to point to MySQL, SQLite, or any SQLAlchemy-compatible DB, and adjust the driver in poetry add. The scaffold doesn’t lock you to Postgres.

What’s the best way to run background tasks (e.g., model inference) in this setup?
FastAPI’s BackgroundTasks works for quick fire-and-forget jobs. For longer jobs, spin up a Celery worker or use a managed queue like Temporal. Keep the worker image similar to the API image so you can reuse the same code base.

Is there a way to generate OpenAPI docs automatically?
FastAPI already serves Swagger UI at /docs and ReDoc at /redoc. Bolt.new doesn’t hide this; just hit those endpoints after deployment.


Key Takeaways

  • Bolt.new gives you a working FastAPI service in seconds – run the CLI, Docker compose, and you’re live.
  • Add async DB support with SQLModel (or async SQLAlchemy) and remember to install greenlet.
  • Deploy to Railway, Render, or Fly.io using the generated Dockerfile; watch for environment-variable port handling and cold-start sleeps.
  • Common failures include missing greenlet, exhausted DB pools, and secret leakage – fix them early.
  • Weigh trade-offs: Bolt.new accelerates prototyping, but you may need to refactor for large-scale production requirements.

If you’ve hit a wall turning a bolt new python backend into a reliable service, I’m happy to roll up my sleeves and help you get it into production. Feel free to check out my hire page for a hands-on engagement.


Working on something similar?

If you're building backend or AI systems and want a second set of senior eyes, let's talk.

Keep reading

Related articles