Enterprise

AI Rules for Backend Teams

Backend teams build APIs, services, and data layers that power applications. AI rules must encode API design conventions, database interaction patterns, error handling standards, and the architectural patterns that keep backend systems reliable.

6 min read¡July 5, 2025

A backend bug affects every consumer simultaneously. AI rules enforce API conventions, query safety, and auth on every endpoint.

REST conventions, N+1 prevention, transaction management, structured errors, and input validation schemas

Backend: APIs, Services, and Data

Backend code serves every frontend, mobile app, and integration. A bug in the backend affects all consumers simultaneously. A slow query degrades every user's experience. A security flaw in an API endpoint exposes every user's data. Backend AI rules must enforce: consistent API design (consumers know what to expect), safe database interactions (no N+1 queries, no unindexed scans), proper error handling (meaningful errors, not stack traces), and security by default (authentication, authorization, input validation on every endpoint).

The backend stack varies by organization: Node.js (Express, Fastify, NestJS), Python (FastAPI, Django), Go (Echo, Gin, standard library), Java (Spring Boot), Rust (Axum, Actix). AI rule: 'Detect the backend framework from package.json, go.mod, requirements.txt, or pom.xml. Generate code using the framework's conventions. NestJS: controllers, services, modules. FastAPI: router functions with type hints. Go: handlers with standard interfaces. Never mix framework patterns.'

The core backend AI rules: every endpoint has authentication and authorization, every database query is parameterized, every error returns a structured response, every external call has a timeout and retry strategy, and every service has health checks and observability.

API Design Conventions

REST conventions: AI rule: 'Resource naming: plural nouns (/users, /orders, not /user, /getOrders). HTTP methods: GET (read), POST (create), PUT (full update), PATCH (partial update), DELETE (remove). Status codes: 200 (success), 201 (created), 204 (no content), 400 (bad request), 401 (unauthorized), 403 (forbidden), 404 (not found), 409 (conflict), 422 (validation error), 500 (server error). The AI must use the correct HTTP method and status code for every endpoint.'

Response format: AI rule: 'Consistent JSON response envelope: { data: {...}, meta: {...} } for success. { error: { code: "VALIDATION_ERROR", message: "...", details: [...] } } for errors. Pagination: { data: [...], meta: { total: 100, page: 1, pageSize: 20, totalPages: 5 } }. The AI generates the same response shape for every endpoint. Consumers should never have to guess the response format.'

API versioning: AI rule: 'Version in the URL path (/api/v1/users) or header (Accept: application/vnd.api+json;version=1). Never change the behavior of an existing API version — add a new version. Deprecation: announce 6 months before removal. The AI generates new endpoints in the current API version and never modifies existing versioned endpoints.'

💡 Consistent Response Envelope Saves Client Dev Time

When every endpoint returns the same shape ({ data, meta } or { error }): the client team writes one response handler that works everywhere. When endpoints return different shapes (some return raw arrays, some wrap in { results }, some use { items }): the client team writes custom handling for each endpoint. The AI should generate the same response envelope for every endpoint — consistency is more valuable than per-endpoint optimization.

Database Interaction Patterns

Query safety: AI rule: 'All queries: parameterized (prepared statements). ORM: use the ORM's query builder (Prisma, Drizzle, SQLAlchemy, GORM). Raw SQL: only when the ORM cannot express the query, and always with parameterized placeholders ($1, ?, :param). Never concatenate user input into SQL strings. The AI must use the project's ORM for all standard CRUD operations.'

N+1 query prevention: AI rule: 'When loading related data: use eager loading (include/join) not lazy loading (separate query per record). Prisma: include: { posts: true }. SQLAlchemy: joinedload(). Drizzle: with clause. If the AI generates a loop that makes a database query per iteration: refactor to a single query with a WHERE IN clause. N+1 queries are the most common backend performance bug.'

Transaction management: AI rule: 'Operations that modify multiple records or tables: wrap in a transaction. If any step fails: the entire transaction rolls back. Pattern: db.transaction(async (tx) => { await tx.insert(...); await tx.update(...); }). Never leave the database in a partially modified state. The AI generates transactions for multi-step mutations by default.'

âš ī¸ N+1 Queries Are the #1 Backend Performance Bug

Loading 100 users with their posts: 1 query for users + 100 queries for posts (one per user) = 101 queries. With eager loading: 1 query for users + 1 query for posts WHERE user_id IN (...) = 2 queries. 101 vs 2 queries. On a database with 10ms latency per query: 1010ms vs 20ms. The AI must detect loops that execute database queries and refactor to batch loading. This single rule prevents the majority of backend performance issues.

Error Handling and Security

Error handling: AI rule: 'Catch errors at the handler level. Return structured error responses (not raw stack traces). Log the full error (including stack trace) server-side. Return a sanitized error to the client (error code + user-friendly message, never internal details). Unexpected errors: return 500 with a generic message. The AI generates error handling middleware that catches unhandled exceptions and returns structured responses.'

Authentication and authorization: AI rule: 'Every endpoint that accesses user data: requires authentication. Authentication middleware: validates the token (JWT, session, API key) before the handler runs. Authorization: checked per endpoint based on the user's role and resource ownership. Pattern: authenticate → authorize → handle. The AI must never generate an endpoint that returns user data without auth middleware.'

Input validation: AI rule: 'Validate all request inputs at the handler level before processing. Body: validate schema (Zod, Joi, Pydantic, Go struct tags). Query parameters: validate types and ranges. Path parameters: validate format (UUID, slug). Reject invalid input with 400/422 and a descriptive error. Never pass unvalidated input to database queries or business logic. The AI generates validation schemas alongside endpoint handlers.'

â„šī¸ Never Return Stack Traces to Clients

A stack trace in an API response reveals: framework version (attackers know which vulnerabilities to try), file paths (internal server structure), database connection details (in some error cases), and business logic structure (function names reveal what the code does). The AI must generate error handling that: logs the full error server-side (for debugging) and returns a sanitized error to the client (error code + user message, no internal details).

Backend AI Rules Summary

Summary of AI rules for backend teams building APIs and services.

  • API design: plural nouns, correct HTTP methods, correct status codes, consistent response envelope
  • Pagination: standardized meta object (total, page, pageSize, totalPages)
  • Database: parameterized queries only. Eager loading to prevent N+1. Transactions for multi-step mutations
  • Error handling: structured responses to clients. Full errors logged server-side. No stack traces in responses
  • Authentication: middleware on every user-data endpoint. Validate tokens before handling
  • Authorization: role and ownership checks per endpoint. Default deny
  • Input validation: Zod/Joi/Pydantic schemas on all inputs. Reject invalid before processing
  • Framework detection: NestJS/FastAPI/Go/Spring patterns. Match the existing framework conventions
AI Rules for Backend Teams — RuleSync Blog