The Backend Bottleneck Is Real — and AI Is the Workaround
Every backend developer knows the drill: scaffolding a REST API, wiring up database queries, debugging a mysterious 500 error, or writing yet another middleware. These tasks eat hours, not because they're hard, but because they're repetitive. According to a 2023 survey by Stack Overflow, developers spend nearly 25% of their time on boilerplate and maintenance. That's a quarter of your day that could go into features, architecture, or — let's be honest — a coffee break.
AI assistants like GitHub Copilot and ChatGPT have changed the game. But most developers use them like a glorified autocomplete, missing the real power: carefully crafted prompts that produce production-ready code. In this guide, I'll share 12 battle-tested prompts for Node.js, FastAPI, and Go. Each one is designed to solve a specific backend problem, from generating a full CRUD API to optimizing N+1 queries. No fluff, just copy-paste-and-adapt templates.
Node.js: From Zero to API in One Prompt
1. Scaffold a REST API with Express and Mongoose
Task: Generate a complete REST API for a blog platform with user authentication, post CRUD, and comment functionality.
Prompt:
You are an expert Node.js developer. Generate a production-ready REST API using Express and Mongoose for a blog platform. Include:
- User model with email/password (bcrypt for hashing)
- JWT authentication (jsonwebtoken)
- Post model with title, content, author (ref User)
- Comment model with text and post reference
- Routes for register, login, CRUD posts, and adding/removing comments
- Error handling middleware
- Input validation using Joi
- Environment variables for secrets (use dotenv)
- Use async/await and try/catch blocks
Provide complete code files with brief explanations.
Example Result (excerpt):
// models/User.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
userSchema.pre('save', async function () {
this.password = await bcrypt.hash(this.password, 10);
});
module.exports = mongoose.model('User', userSchema);
Why it works: The prompt specifies the exact stack, models, and features. The AI fills in the boilerplate, and you review the logic. This saves about 2 hours of manual setup.
2. Optimize a Slow Database Query
Task: Refactor a query that suffers from N+1 problem.
Prompt:
Here's a Mongoose query that fetches posts and their authors. It makes a separate DB call for each post. Optimize it to use a single query with population or aggregation. Explain the change.
const posts = await Post.find();
for (const post of posts) {
post.author = await User.findById(post.authorId);
}
Example Result:
const posts = await Post.find().populate('author');
The AI explains that populate performs a join-like operation in MongoDB, reducing round trips from N+1 to 2.
3. Write a Custom Middleware for Request Logging
Task: Create a middleware that logs method, URL, response time, and status code.
Prompt:
Write an Express middleware that logs the HTTP method, URL, response time (in ms), and status code for each request. Use the `response-time` package or manual Date.now(). Output should be a single line per request. Include comments.
Example Result:
const logger = (req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${duration}ms`);
});
next();
};
FastAPI: Async Power with AI
4. Build a CRUD API with SQLAlchemy and Pydantic
Task: Generate a FastAPI app for a task manager with SQLite.
Prompt:
Create a FastAPI application for a task manager. Use SQLAlchemy (ORM) and Pydantic for schemas. Include:
- Task model: id, title, description, due_date, completed
- Endpoints: create, read all, read one, update, delete
- Use async SQLAlchemy (or sync with explanation)
- Add CORS middleware for localhost:3000
- Include request validation and proper HTTP status codes
Provide code with file structure.
Example Result (excerpt):
# main.py
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from . import models, schemas
app = FastAPI()
@app.post("/tasks", response_model=schemas.Task)
def create_task(task: schemas.TaskCreate, db: Session = Depends(get_db)):
db_task = models.Task(**task.dict())
db.add(db_task)
db.commit()
db.refresh(db_task)
return db_task
5. Create a Background Task for Email Sending
Task: Implement a background task that sends a welcome email after user registration.
Prompt:
Using FastAPI's BackgroundTasks, write a function that sends a simple email (simulate with print) after a user registers. Show the endpoint and the background task definition. Include error handling.
Example Result:
from fastapi import BackgroundTasks
def send_welcome_email(email: str):
# Simulate sending
print(f"Sending welcome to {email}")
@app.post("/register")
async def register(user: schemas.UserCreate, background_tasks: BackgroundTasks):
# create user in DB
background_tasks.add_task(send_welcome_email, user.email)
return {"message": "User created"}
6. Generate OpenAPI Schema and Swagger UI Customizations
Task: Customize the default Swagger UI theme and add tags.
Prompt:
Using FastAPI, configure the app to:
- Set title, description, and version
- Use a custom Swagger UI CSS from a CDN
- Group endpoints by tags (e.g., "users", "tasks")
Provide the code.
Example Result:
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
app = FastAPI(title="Task Manager", version="1.0.0",
description="API for managing tasks")
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title="Custom Docs",
swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css"
)
Go: High Performance, AI-Accelerated
7. Generate a REST API with Gin and GORM
Task: Build a simple bookstore API.
Prompt:
Write a Go application using Gin and GORM for a bookstore. Include:
- Book model: ID, Title, Author, Price
- Endpoints: GET /books, GET /books/:id, POST /books, PUT /books/:id, DELETE /books/:id
- Use SQLite for database
- Handle errors with proper HTTP status codes
- Use environment variables for port
Provide the full main.go and model files.
Example Result (excerpt):
func main() {
r := gin.Default()
db := initDB()
r.GET("/books", getBooks(db))
r.POST("/books", createBook(db))
r.Run(":8080")
}
8. Write a Concurrency-Safe Cache with Mutex
Task: Implement a simple in-memory cache for a Go service.
Prompt:
Implement a thread-safe cache in Go using sync.RWMutex. Include methods: Get, Set, Delete, and a cleanup function for expired items (with TTL). Provide an example usage.
Example Result:
type Cache struct {
mu sync.RWMutex
items map[string]item
}
type item struct {
value interface{}
expiration int64
}
func (c *Cache) Set(key string, value interface{}, ttl time.Duration) {
c.mu.Lock()
c.items[key] = item{value: value, expiration: time.Now().Add(ttl).UnixNano()}
c.mu.Unlock()
}
9. Generate a gRPC Service with Protobuf
Task: Create a gRPC service for a user profile.
Prompt:
Define a protobuf message for a User (id, name, email) and a service with GetUser and CreateUser. Write the server implementation in Go using grpc-go. Include error handling.
Example Result:
syntax = "proto3";
package user;
message User {
int32 id = 1;
string name = 2;
string email = 3;
}
service UserService {
rpc GetUser(GetUserRequest) returns (User);
}
The AI generates the Go server code with proper registration.
Cross-Language: Error Handling and Refactoring
10. Design a Consistent Error Response Format
Task: Create a uniform error structure for an API.
Prompt:
Design a standard error response format for a REST API. It should include: error code (string), message (human-readable), details (optional object). Show how to implement it in Node.js, FastAPI, and Go. Give examples of error responses for 400, 404, and 500.
Example Result:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid email format",
"details": { "field": "email" }
}
}
11. Refactor Spaghetti Code into Clean Layers
Task: Refactor a messy backend function.
Prompt:
Here's a Python function that handles user registration (validation, DB, email). Refactor it into service, repository, and controller layers. Use dependency injection. Show the refactored code.
Example Result: The AI splits the function into UserController, UserService, and UserRepository, making it testable.
12. Write Unit Tests for an Existing API
Task: Generate tests for a FastAPI endpoint.
Prompt:
Write pytest tests for the following FastAPI endpoint. Use TestClient, mock the database, and test success and error cases. Provide the code.
@app.get("/users/{id}")
def get_user(id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
Example Result:
def test_get_user_success(client, mocker):
mock_db = mocker.Mock()
mock_db.query.return_value.filter.return_value.first.return_value = User(id=1, name="Alice")
response = client.get("/users/1")
assert response.status_code == 200
The Bottom Line
AI prompts are not magic — they're a force multiplier. With the right instructions, you can cut boilerplate time by 50-70%. But remember: always review the generated code. AI can't replace your judgment, especially on security and architecture. Use these prompts as a starting point, adapt them to your stack, and you'll ship faster than ever.
Now go ahead — copy a prompt, paste it into your favorite AI tool, and watch your backend build itself. And if you've got a killer prompt of your own, share it in the comments below.
Comments