Building a production-ready FastAPI backend with Claude Opus and Cursor
If you're trying to ship a complex backend in 2026, stop treating LLMs like a chat window. I spent last Tuesday migrating a legacy Django app to FastAPI and found that the "chat and paste" loop is where most devs lose time. The secret isn't just the model—it's using Claude 3 Opus inside an IDE that actually understands your file tree.
Here is exactly how I set up my environment to avoid the "hallucination loop" where the AI suggests a library that hasn't been updated since 2023.
Why Opus still beats the faster models for architecture #
I've tried the latest "small" models for speed, but they fail at global state management. When I asked a smaller model to implement a PostgreSQL connection pool across five different modules, it forgot the singleton pattern by the third file.
Opus doesn't. It's slower—expect a 4-8 second lag for a complex prompt—but it understands the dependency graph. For raw logic, use Haiku or Sonnet. For the initial schema and the "How do these ten files talk to each other?" phase, Opus is the only choice.
Setting up the "Power Stack" for 2026 #
Don't just use the web browser. You need a tight loop.
-
Install Cursor (the fork of VS Code).
-
Go to Settings -> Models -> Toggle on
claude-3-opus. -
Index your codebase. This is non-negotiable. If the AI isn't reading your
.env.exampleandrequirements.txt, it will guess your variable names and break your build.
Real-world implementation: The Async Database Pattern #
I hit a wall last week with an asyncpg connection leak. The AI kept suggesting await conn.close() inside a loop, which is a disaster for performance. I had to force it to use a context manager.
Here is the exact prompt and the resulting code that actually worked.
The Prompt:
"Refactor my database.py to use a connection pool with asyncpg. Ensure the pool is created once on startup and closed on shutdown. Use a dependency injection pattern for FastAPI routes. Stop suggesting individual connection closes; I need a managed pool."
The Result (and what you should look for):
import asyncpg
from fastapi import FastAPI, Depends
class Database:
def __init__(self):
self.pool = None
async def connect(self):
self.pool = await asyncpg.create_pool(
dsn="postgresql://user:pass@localhost/db",
min_size=1,
max_size=10
)
async def disconnect(self):
await self.pool.close()
db = Database()
async def get_db():
async with db.pool.acquire() as connection:
yield connection
app = FastAPI()
@app.on_event("startup")
async def startup():
await db.connect()
@app.on_event("shutdown")
async def shutdown():
await db.disconnect()
If your AI gives you a version without the acquire() context manager, it's hallucinating a simplified version. Fix it immediately or you'll see PoolExhaustedError the moment you hit 10 concurrent users.
Stop prompting and start mapping #
The biggest mistake I see juniors make is writing 500-word prompts. It's noise. Instead, I use a .cursorrules file in the root of my project. This acts as a permanent "system prompt" that the AI reads before every single interaction.
My current .cursorrules looks like this:
- Always use Type Hints for function arguments.
- Use Pydantic v2 for all schemas (do not use v1).
- Prefer
async defoverdeffor all DB operations. - If a library is deprecated, flag it before suggesting it.
This saves me from repeating "use Pydantic v2" every three prompts.
Handling the "Context Window" crash #
Even with the massive context of Opus, it eventually forgets what happened in the first file if the project gets huge. When you feel the AI starting to loop or suggest code that contradicts a file it wrote an hour ago, do this:
-
Create a
docs/context.mdfile. -
Manually list the current state: "Auth is handled by JWT in
auth.py, User model is inmodels.py, using PostgreSQL." -
Reference that file explicitly: "@context.md, based on the current state, implement the password reset logic."
This is essentially a manual RAG (Retrieval-Augmented Generation) process. It's annoying, but it's the only way to maintain 100% accuracy in a project with more than 20 files.
Comparing the 2026 toolset #
I've spent a few thousand dollars on API credits this year. Here is the breakdown of what actually helps.
| Tool | Use Case | The "Gotcha" |
| :--- | :--- | :--- |
| Claude Opus | Complex Architecture / Debugging | Slow response time; expensive |
| Cursor | General Coding / Refactoring | Indexing can occasionally lag |
| Windsurf | Agentic workflows / Terminal control | Higher CPU usage during indexing |
| Claude Code | CLI-based rapid iteration | Lacks visual diffs compared to IDEs |
If you want to automate the repetitive parts of this—like updating your context files or syncing your API specs—you should look into building Workflows that connect your LLM to your actual git commits.
Joining the community to stop guessing #
The hardest part of AI coding isn't the syntax; it's knowing when the AI is lying to you. I spent four hours debugging a "feature" that didn't exist in the library version I was using because the AI was confident it did.
That's why I joined PromptCube. It's not just about sharing prompts; it's about seeing how other senior devs handle the "drift" between model versions. When you see someone post a specific fix for a Claude 3.5 vs 3.0 regression, it saves you a whole afternoon of head-scratching.
Joining is straightforward. You basically enter the ecosystem, start sharing your .cursorrules or specific prompt chains, and get feedback from people who are actually shipping code, not just "prompt engineers" who have never touched a terminal.
When to ditch Opus #
To be fair, Opus is overkill for everything. If you're just writing a CSS grid or a simple React component, using Opus is like using a sledgehammer to crack a nut. Switch to a faster, cheaper model for the UI layer. Keep Opus for the data layer, the security logic, and the initial system design.
If it takes more than 10 seconds to generate a response and it's just a boilerplate function, you're wasting money.
Next Cloudflare Workers just got a massive Node.js compatibility boost via a rewritten →
an AI side-hustle playbook, with plenty of directly applicable cases.