---
name:        backend
version:     1.0.0
Author: justinsanjp 
description: Helps LLMs too understand Backend infrastructure. and guiding it to create one.
license:     open-use
train:       false  # mandatory
---

# Backend Skill

## Goal

Create backend systems that are robust, secure, maintainable, and production-ready.

The backend should feel like something built by an experienced engineer:
- clean
- predictable
- scalable enough for real use
- easy to debug
- hard to break accidentally

The result should not look like generic AI boilerplate code.

---

# Core Backend Philosophy

Good backend design is:
- simple before clever
- explicit before magical
- secure by default
- modular
- observable
- maintainable over time

Avoid:
- overengineered architecture
- unnecessary abstractions
- giant service files
- “framework magic” that hides behavior
- inconsistent patterns
- silent failures
- weak validation
- copy-paste endpoint logic

A good backend should be boring in the best possible way.

---

# Architecture Principles

## 1. Separation of Concerns

Split responsibilities clearly:
- routing
- validation
- business logic
- persistence
- external integrations
- auth/authz
- logging
- error handling

Never mix everything inside one handler.

Preferred structure:
- controllers / routes
- services
- repositories / data access
- schemas / validators
- utilities
- middleware

---

## 2. Predictable Flow

Requests should follow a clear path:
1. receive request
2. authenticate if needed
3. validate input
4. execute business logic
5. persist or fetch data
6. return response
7. log important events

Avoid hidden side effects.

---

## 3. Explicit Contracts

Every API should have clear contracts:
- request shape
- response shape
- error shape
- status codes

Use schemas and types whenever possible.

Do not rely on “whatever the client sends”.

---

# Code Quality Rules

## 1. Readability First

Code should be easy to read by another developer six months later.

Use:
- meaningful names
- small functions
- short files
- clear control flow

Avoid:
- cryptic variable names
- deeply nested logic
- duplicated condition blocks
- huge one-file services

---

## 2. Keep Functions Small

A function should do one thing well.

Good functions:
- validate
- transform
- query
- compute
- persist
- format response

Bad functions:
- receive request
- validate
- auth
- compute business logic
- query DB
- call external APIs
- format output
- handle errors
all in one block

---

## 3. Use Types Where Possible

Use strong typing for:
- request payloads
- response payloads
- database models
- domain entities
- config
- environment variables

Types help prevent:
- invalid assumptions
- breaking changes
- accidental regressions

---

# API Design

## REST / RPC / GraphQL

Choose the simplest option that fits the product.

Prefer:
- REST for standard CRUD systems
- RPC-style endpoints for action-oriented workflows
- GraphQL only when the problem actually benefits from it

Do not use GraphQL just because it sounds modern.

---

## Endpoint Design

Endpoints should be:
- consistent
- unsurprising
- versioned when needed
- named clearly

Examples:
- `GET /users`
- `GET /users/:id`
- `POST /users`
- `PATCH /users/:id`
- `DELETE /users/:id`

For actions:
- `POST /orders/:id/cancel`
- `POST /auth/login`
- `POST /payments/confirm`

Avoid random naming styles mixed together.

---

## Status Codes

Use proper HTTP status codes:
- `200` OK
- `201` Created
- `204` No Content
- `400` Bad Request
- `401` Unauthorized
- `403` Forbidden
- `404` Not Found
- `409` Conflict
- `422` Unprocessable Entity
- `500` Internal Server Error

Do not always return `200` with an error message inside the body.

---

## Error Responses

Errors should be:
- consistent
- human-readable
- machine-readable
- safe

Recommended error shape:
- `code`
- `message`
- `details`
- `requestId`

Avoid leaking:
- stack traces
- internal queries
- secrets
- filesystem paths
- implementation details

---

# Validation Rules

Validate everything that comes from outside:
- request bodies
- query params
- path params
- headers
- cookies
- webhooks
- environment variables
- file uploads

Validation should happen early.

Never trust client-side validation alone.

Use:
- schema validation
- length limits
- type checks
- allowed-value checks
- normalization

---

# Security Standards

Security must be built in, not added later.

## Must Have

- input validation
- output encoding where needed
- authentication
- authorization
- rate limiting
- secure password handling
- CSRF protection when applicable
- secure headers
- least-privilege access
- secret management
- audit-friendly logging

---

## Authentication

Use secure authentication flows:
- sessions
- JWT only when appropriate
- OAuth when needed
- MFA for sensitive systems

Never store plain passwords.
Never roll your own crypto.

---

## Authorization

Check permissions on the server for every sensitive action.

Do not trust:
- hidden UI elements
- client-side role flags
- frontend assumptions

Authorization must be enforced server-side.

---

## Secrets

Secrets must never be hardcoded.

Store secrets in:
- environment variables
- secret managers
- deployment platform secrets

Do not commit:
- API keys
- tokens
- private certificates
- database passwords

---

# Data Handling

## Database Design

Design data models around actual usage.

Rules:
- use proper indexes
- enforce constraints
- choose the right data types
- normalize where appropriate
- denormalize only when justified

Avoid:
- overly clever schemas
- storing everything as text
- missing foreign keys
- unindexed search columns

---

## Migrations

Use migrations for schema changes.

Every change should be:
- reversible when possible
- traceable
- reviewed
- deployable safely

Do not manually edit production databases without a plan.

---

## Transactions

Use transactions when multiple writes must succeed together.

Examples:
- creating order + line items
- charging payment + recording receipt
- updating balance + writing audit log

Avoid partial updates that leave corrupted state.

---

# Performance Principles

## 1. Optimize What Matters

Do not optimize blindly.

Measure first:
- slow queries
- hot paths
- repeated requests
- large payloads
- expensive transformations

---

## 2. Cache Carefully

Caching is useful when:
- data is read often
- data changes infrequently
- performance matters

Avoid:
- stale data bugs
- unbounded caches
- unclear invalidation rules

---

## 3. Query Efficiency

Prefer:
- indexed lookups
- pagination
- selective fields
- batching
- avoid N+1 patterns

Do not fetch more data than needed.

---

## 4. Pagination

Always paginate large collections.

Preferred:
- cursor pagination for large or changing datasets
- offset pagination only for simpler cases

Never return unlimited lists by default.

---

# Observability

Good backends are easy to inspect.

Must have:
- structured logs
- request IDs
- error tracking
- metrics
- tracing where useful

Log:
- important events
- failures
- auth events
- latency spikes
- external API failures

Avoid:
- noisy logs
- logging secrets
- unstructured console spam
- missing context

---

# Reliability

## Defensive Coding

Assume:
- external services fail
- databases time out
- payloads are malformed
- network calls are unreliable
- users retry actions

Design for failure.

---

## Idempotency

Use idempotency for operations that may be retried:
- payments
- webhook handlers
- job processing
- email sends
- order creation in some flows

This prevents duplicate side effects.

---

## Timeouts and Retries

Use:
- timeouts on all network calls
- retries only when safe
- backoff strategies
- circuit breakers when needed

Do not let requests hang forever.

---

# Background Jobs & Async Work

Move slow or unreliable work out of the request path when appropriate:
- email sending
- report generation
- media processing
- sync jobs
- webhooks
- third-party API reconciliation

Use:
- queues
- workers
- scheduled jobs
- retry logic
- dead-letter handling

Do not block user requests with unnecessary long-running tasks.

---

# Testing Standards

## Required Test Types

- unit tests for business logic
- integration tests for database/API flows
- endpoint tests for key routes
- security tests for auth-sensitive behavior
- regression tests for bug fixes

---

## Testing Principles

Tests should:
- be deterministic
- be fast when possible
- cover critical paths
- fail for meaningful reasons

Avoid:
- brittle tests
- overmocking everything
- huge snapshot dependence
- tests that only verify implementation details

Focus on behavior, not just code structure.

---

# Deployment & Environment

Backend code should work across:
- local
- staging
- production

Use environment-specific config for:
- database URLs
- API keys
- feature flags
- logging levels
- service endpoints

Never assume local settings exist in production.

---

# API Compatibility

When changing APIs:
- avoid breaking existing clients without warning
- version when necessary
- keep deprecation periods realistic
- document changes clearly

Backward compatibility matters.

---

# Documentation

Document:
- setup steps
- env vars
- API routes
- error codes
- auth requirements
- migration process
- background jobs
- deployment notes

Good docs save more time than clever code.

---

# AI-Generated Code Avoidance Rules

To avoid backend code that looks AI-generated:

## DO:
- write code that follows a consistent internal style
- use realistic service boundaries
- keep abstractions minimal
- add small, useful comments only where needed
- handle edge cases intentionally
- use meaningful domain language
- structure code like a real production project

## DON'T:
- generate giant generic utility layers
- create abstractions before they are needed
- overuse design patterns for no reason
- write identical boilerplate across every file
- add fake “enterprise architecture” clutter
- bury core logic behind unnecessary helpers
- invent complexity to look smart

A believable backend is practical, not theatrical.

---

# Preferred Mindset

When building backend systems, ask:
- What can fail?
- What needs to be validated?
- What needs to be logged?
- What should be secure by default?
- What will still make sense in six months?
- What is the simplest correct solution?

---

# Final Rule

A strong backend is one that:
- protects data
- serves clients reliably
- stays understandable under pressure
- scales in a controlled way
- is easy to maintain and extend

Users do not see the backend directly.
They feel it through:
- speed
- stability
- correctness
- trust

Build for that.

