Agent skill

Backend Patterns

by affaan-m in affaan-m/ECC

Patrones de arquitectura backend, diseño de API, optimización de base de datos y buenas prácticas del lado del servidor para Node.js, Express y rutas API de Next.js.

MITAuto-check passedBackend & APIs

Install Backend Patterns

skills CLI
$ npx skills add affaan-m/ECC --skill backend-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install affaan-m/ECC backend-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/affaan-m/ECC.git skills-src && mkdir -p .claude/skills && cp -r skills-src/docs/es/skills/backend-patterns .claude/skills/backend-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
backend-patterns
GitHub stars
276k
Token cost
~3.4k tokens
SKILL.md length
262 words
Files
1
Skills in repo
673
Repo updated
First seen
Licence
MIT

At a glance

Patrones de arquitectura backend, diseño de API, optimización de base de datos y buenas prácticas del lado del servidor para Node.js, Express y rutas API de Next.js.

  • Tasks that involve Backend development
  • SKILL.md covers Cuándo Activar, Patrones de Diseño de API, Patrones de Base de Datos and Estrategias de Caché, plus 5 more sections
  • Needs JWT_SECRET

What it does

Backend Patterns is an agent skill from affaan-m/ECC. Patrones de arquitectura backend, diseño de API, optimización de base de datos y buenas prácticas del lado del servidor para Node.js, Express y rutas API de Next.js.

Its SKILL.md is about 3.4k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering Backend development. It works with Next.js and Node.js. The repository describes itself as: The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. The licence is MIT.

When your agent uses it

  • Tasks that involve Backend development

Example prompts

  • “Use the backend-patterns skill to patrone de arquitectura backend, diseño de API, optimización de base de datos y buenas prácticas del lado del…”
  • “/backend-patterns”

Requirements

  • Node.js
  • A credential in JWT_SECRET

What it can do on your machine

Read from SKILL.md and the folder at commit ef648e0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • JWT_SECRET

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Backend Patterns loads about 3.4k tokens when it runs. Until then it costs about 46 tokens; SKILL.md has 262 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~46
When it runs · the whole SKILL.md, loaded when a task matches
~3.4k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from affaan-m/ECC at commit ef648e0, republished under its MIT licence (© affaan-m). 262 words, ~3,410 tokens.

Download SKILL.mdSave it as .claude/skills/backend-patterns/SKILL.md (or your agent's skills folder).
name
backend-patterns
description
Patrones de arquitectura backend, diseño de API, optimización de base de datos y buenas prácticas del lado del servidor para Node.js, Express y rutas API de Next.js.
origin
ECC

Patrones de Desarrollo Backend

Patrones de arquitectura backend y buenas prácticas para aplicaciones del lado del servidor escalables.

Cuándo Activar

  • Diseñar endpoints de API REST o GraphQL
  • Implementar capas de repositorio, servicio o controlador
  • Optimizar consultas de base de datos (N+1, indexación, connection pooling)
  • Agregar caché (Redis, en memoria, headers de caché HTTP)
  • Configurar trabajos en segundo plano o procesamiento asíncrono
  • Estructurar manejo de errores y validación para APIs
  • Construir middleware (auth, logging, rate limiting)

Patrones de Diseño de API

Estructura de API RESTful
typescript
// PASS: URLs basadas en recursos
GET    /api/markets                 # Listar recursos
GET    /api/markets/:id             # Obtener recurso individual
POST   /api/markets                 # Crear recurso
PUT    /api/markets/:id             # Reemplazar recurso
PATCH  /api/markets/:id             # Actualizar recurso
DELETE /api/markets/:id             # Eliminar recurso

// PASS: Parámetros de consulta para filtrado, ordenamiento, paginación
GET /api/markets?status=active&sort=volume&limit=20&offset=0
Patrón Repository
typescript
// Abstraer la lógica de acceso a datos
interface MarketRepository {
  findAll(filters?: MarketFilters): Promise<Market[]>
  findById(id: string): Promise<Market | null>
  create(data: CreateMarketDto): Promise<Market>
  update(id: string, data: UpdateMarketDto): Promise<Market>
  delete(id: string): Promise<void>
}

class SupabaseMarketRepository implements MarketRepository {
  async findAll(filters?: MarketFilters): Promise<Market[]> {
    let query = supabase.from('markets').select('*')

    if (filters?.status) {
      query = query.eq('status', filters.status)
    }

    if (filters?.limit) {
      query = query.limit(filters.limit)
    }

    const { data, error } = await query

    if (error) throw new Error(error.message)
    return data
  }

  // Otros métodos...
}
Patrón de Capa de Servicio
typescript
// Lógica de negocio separada del acceso a datos
class MarketService {
  constructor(private marketRepo: MarketRepository) {}

  async searchMarkets(query: string, limit: number = 10): Promise<Market[]> {
    // Lógica de negocio
    const embedding = await generateEmbedding(query)
    const results = await this.vectorSearch(embedding, limit)

    // Obtener datos completos
    const markets = await this.marketRepo.findByIds(results.map(r => r.id))

    // Ordenar por similitud
    return markets.sort((a, b) => {
      const scoreA = results.find(r => r.id === a.id)?.score || 0
      const scoreB = results.find(r => r.id === b.id)?.score || 0
      return scoreA - scoreB
    })
  }

  private async vectorSearch(embedding: number[], limit: number) {
    // Implementación de búsqueda vectorial
  }
}
Patrón Middleware
typescript
// Pipeline de procesamiento de request/response
export function withAuth(handler: NextApiHandler): NextApiHandler {
  return async (req, res) => {
    const token = req.headers.authorization?.replace('Bearer ', '')

    if (!token) {
      return res.status(401).json({ error: 'Unauthorized' })
    }

    try {
      const user = await verifyToken(token)
      req.user = user
      return handler(req, res)
    } catch (error) {
      return res.status(401).json({ error: 'Invalid token' })
    }
  }
}

// Uso
export default withAuth(async (req, res) => {
  // El handler tiene acceso a req.user
})

Patrones de Base de Datos

Optimización de Consultas
typescript
// PASS: BIEN: Seleccionar solo las columnas necesarias
const { data } = await supabase
  .from('markets')
  .select('id, name, status, volume')
  .eq('status', 'active')
  .order('volume', { ascending: false })
  .limit(10)

// FAIL: MAL: Seleccionar todo
const { data } = await supabase
  .from('markets')
  .select('*')
Prevención de Problema N+1
typescript
// FAIL: MAL: Problema de consulta N+1
const markets = await getMarkets()
for (const market of markets) {
  market.creator = await getUser(market.creator_id)  // N consultas
}

// PASS: BIEN: Obtención en lote
const markets = await getMarkets()
const creatorIds = markets.map(m => m.creator_id)
const creators = await getUsers(creatorIds)  // 1 consulta
const creatorMap = new Map(creators.map(c => [c.id, c]))

markets.forEach(market => {
  market.creator = creatorMap.get(market.creator_id)
})
Patrón de Transacción
typescript
async function createMarketWithPosition(
  marketData: CreateMarketDto,
  positionData: CreatePositionDto
) {
  // Usar transacción de Supabase
  const { data, error } = await supabase.rpc('create_market_with_position', {
    market_data: marketData,
    position_data: positionData
  })

  if (error) throw new Error('Transaction failed')
  return data
}

// Función SQL en Supabase
CREATE OR REPLACE FUNCTION create_market_with_position(
  market_data jsonb,
  position_data jsonb
)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
  -- La transacción comienza automáticamente
  INSERT INTO markets VALUES (market_data);
  INSERT INTO positions VALUES (position_data);
  RETURN jsonb_build_object('success', true);
EXCEPTION
  WHEN OTHERS THEN
    -- El rollback ocurre automáticamente
    RETURN jsonb_build_object('success', false, 'error', SQLERRM);
END;
$$;

Estrategias de Caché

Capa de Caché con Redis
typescript
class CachedMarketRepository implements MarketRepository {
  constructor(
    private baseRepo: MarketRepository,
    private redis: RedisClient
  ) {}

  async findById(id: string): Promise<Market | null> {
    // Verificar caché primero
    const cached = await this.redis.get(`market:${id}`)

    if (cached) {
      return JSON.parse(cached)
    }

    // Cache miss - obtener de base de datos
    const market = await this.baseRepo.findById(id)

    if (market) {
      // Cachear por 5 minutos
      await this.redis.setex(`market:${id}`, 300, JSON.stringify(market))
    }

    return market
  }

  async invalidateCache(id: string): Promise<void> {
    await this.redis.del(`market:${id}`)
  }
}
Patrón Cache-Aside
typescript
async function getMarketWithCache(id: string): Promise<Market> {
  const cacheKey = `market:${id}`

  // Intentar caché
  const cached = await redis.get(cacheKey)
  if (cached) return JSON.parse(cached)

  // Cache miss - obtener de DB
  const market = await db.markets.findUnique({ where: { id } })

  if (!market) throw new Error('Market not found')

  // Actualizar caché
  await redis.setex(cacheKey, 300, JSON.stringify(market))

  return market
}

Patrones de Manejo de Errores

Manejador de Errores Centralizado
typescript
class ApiError extends Error {
  constructor(
    public statusCode: number,
    public message: string,
    public isOperational = true
  ) {
    super(message)
    Object.setPrototypeOf(this, ApiError.prototype)
  }
}

export function errorHandler(error: unknown, req: Request): Response {
  if (error instanceof ApiError) {
    return NextResponse.json({
      success: false,
      error: error.message
    }, { status: error.statusCode })
  }

  if (error instanceof z.ZodError) {
    return NextResponse.json({
      success: false,
      error: 'Validation failed',
      details: error.errors
    }, { status: 400 })
  }

  // Registrar errores inesperados
  console.error('Unexpected error:', error)

  return NextResponse.json({
    success: false,
    error: 'Internal server error'
  }, { status: 500 })
}

// Uso
export async function GET(request: Request) {
  try {
    const data = await fetchData()
    return NextResponse.json({ success: true, data })
  } catch (error) {
    return errorHandler(error, request)
  }
}
Reintentos con Backoff Exponencial
typescript
async function fetchWithRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3
): Promise<T> {
  let lastError: Error

  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn()
    } catch (error) {
      lastError = error as Error

      if (i < maxRetries - 1) {
        // Backoff exponencial: 1s, 2s, 4s
        const delay = Math.pow(2, i) * 1000
        await new Promise(resolve => setTimeout(resolve, delay))
      }
    }
  }

  throw lastError!
}

// Uso
const data = await fetchWithRetry(() => fetchFromAPI())

Autenticación y Autorización

Validación de Token JWT
typescript
import jwt from 'jsonwebtoken'

interface JWTPayload {
  userId: string
  email: string
  role: 'admin' | 'user'
}

export function verifyToken(token: string): JWTPayload {
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload
    return payload
  } catch (error) {
    throw new ApiError(401, 'Invalid token')
  }
}

export async function requireAuth(request: Request) {
  const token = request.headers.get('authorization')?.replace('Bearer ', '')

  if (!token) {
    throw new ApiError(401, 'Missing authorization token')
  }

  return verifyToken(token)
}

// Uso en ruta API
export async function GET(request: Request) {
  const user = await requireAuth(request)

  const data = await getDataForUser(user.userId)

  return NextResponse.json({ success: true, data })
}
Control de Acceso Basado en Roles
typescript
type Permission = 'read' | 'write' | 'delete' | 'admin'

interface User {
  id: string
  role: 'admin' | 'moderator' | 'user'
}

const rolePermissions: Record<User['role'], Permission[]> = {
  admin: ['read', 'write', 'delete', 'admin'],
  moderator: ['read', 'write', 'delete'],
  user: ['read', 'write']
}

export function hasPermission(user: User, permission: Permission): boolean {
  return rolePermissions[user.role].includes(permission)
}

export function requirePermission(permission: Permission) {
  return (handler: (request: Request, user: User) => Promise<Response>) => {
    return async (request: Request) => {
      const user = await requireAuth(request)

      if (!hasPermission(user, permission)) {
        throw new ApiError(403, 'Insufficient permissions')
      }

      return handler(request, user)
    }
  }
}

// Uso - HOF envuelve el handler
export const DELETE = requirePermission('delete')(
  async (request: Request, user: User) => {
    // El handler recibe el usuario autenticado con permiso verificado
    return new Response('Deleted', { status: 200 })
  }
)

Rate Limiting

El rate limiting debe usar un almacén compartido como Redis, un gateway, o el limitador nativo de la plataforma. No usar contadores en memoria por proceso para APIs de producción: se reinician al desplegarse, se dividen entre réplicas y fallan abiertamente en entornos serverless o multi-instancia.

Mantener la capa backend responsable de elegir el punto de integración y la forma del error; usar api-design para el contrato HTTP y security-review para la revisión de casos de abuso.

Trabajos en Segundo Plano y Colas

Patrón de Cola Simple
typescript
class JobQueue<T> {
  private queue: T[] = []
  private processing = false

  async add(job: T): Promise<void> {
    this.queue.push(job)

    if (!this.processing) {
      this.process()
    }
  }

  private async process(): Promise<void> {
    this.processing = true

    while (this.queue.length > 0) {
      const job = this.queue.shift()!

      try {
        await this.execute(job)
      } catch (error) {
        console.error('Job failed:', error)
      }
    }

    this.processing = false
  }

  private async execute(job: T): Promise<void> {
    // Lógica de ejecución del trabajo
  }
}

// Uso para indexar markets
interface IndexJob {
  marketId: string
}

const indexQueue = new JobQueue<IndexJob>()

export async function POST(request: Request) {
  const { marketId } = await request.json()

  // Agregar a la cola en lugar de bloquear
  await indexQueue.add({ marketId })

  return NextResponse.json({ success: true, message: 'Job queued' })
}

Logging y Monitoreo

Logging Estructurado
typescript
interface LogContext {
  userId?: string
  requestId?: string
  method?: string
  path?: string
  [key: string]: unknown
}

class Logger {
  log(level: 'info' | 'warn' | 'error', message: string, context?: LogContext) {
    const entry = {
      timestamp: new Date().toISOString(),
      level,
      message,
      ...context
    }

    console.log(JSON.stringify(entry))
  }

  info(message: string, context?: LogContext) {
    this.log('info', message, context)
  }

  warn(message: string, context?: LogContext) {
    this.log('warn', message, context)
  }

  error(message: string, error: Error, context?: LogContext) {
    this.log('error', message, {
      ...context,
      error: error.message,
      stack: error.stack
    })
  }
}

const logger = new Logger()

// Uso
export async function GET(request: Request) {
  const requestId = crypto.randomUUID()

  logger.info('Fetching markets', {
    requestId,
    method: 'GET',
    path: '/api/markets'
  })

  try {
    const markets = await fetchMarkets()
    return NextResponse.json({ success: true, data: markets })
  } catch (error) {
    logger.error('Failed to fetch markets', error as Error, { requestId })
    return NextResponse.json({ error: 'Internal error' }, { status: 500 })
  }
}

Recuerda: Los patrones backend permiten aplicaciones del lado del servidor escalables y mantenibles. Elige los patrones que se ajusten a tu nivel de complejidad.

© affaan-m, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in docs/es/skills/backend-patterns of affaan-m/ECC.

Open the folder on GitHubat commit ef648e0

Compare with similar skills

Backend Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Backend Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Backend Patterns this skillaffaan-m/ECC276k—~3.4kAutomated safety check: PassMIT
Backend PatternshellangleZ/burn-in-cceverywhere-ralph11217 repos~3.3kAutomated safety check: PassNone
PayRam Checkout IntegrationPayRam/payram-mcp158—~3.4kAutomated safety check: NotesNone
Fullstack DevHHU3637kr/skills1453 repos~8.6kAutomated safety check: NotesMIT
Backend Patternsxu-xiang/everything-claude-code-zh2k—~3.2kAutomated safety check: PassMIT
Backend Patternsxu-xiang/everything-claude-code-zh2k—~3.1kAutomated safety check: PassMIT

Similar skills

  • Backend Patterns

    hellangleZ/burn-in-cceverywhere-ralph

    Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes.

    112 GitHub starsUsed in 17 repos~3.3k tokens
    Backend & APIsAuto-check passed
  • Adds crypto checkout to a web app with PayRam: create a payment from your backend, send the customer to the payment page, then confirm the result.

    158 GitHub stars~3.4k tokensUpdated today
    Backend & APIsAuto-check: notes
  • Fullstack Dev

    HHU3637kr/skills

    Full-stack backend architecture and frontend-backend integration guide.

    145 GitHub starsUsed in 3 repos~8.6k tokens
    Backend & APIsAuto-check: notes
  • Backend Patterns

    xu-xiang/everything-claude-code-zh

    后端架构模式、API 设计、数据库优化以及适用于 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

    2k GitHub stars~3.2k tokensUpdated 7 mo ago
    Backend & APIsAuto-check passed
  • Backend Patterns

    xu-xiang/everything-claude-code-zh

    后端架构模式、API 设计、数据库优化以及 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

    2k GitHub stars~3.1k tokensUpdated 7 mo ago
    Backend & APIsAuto-check passed
  • Backend Patterns

    xu-xiang/everything-claude-code-zh

    后端架构模式、API 设计、数据库优化以及针对 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

    2k GitHub stars~3.2k tokensUpdated 7 mo ago
    Backend & APIsAuto-check passed

More from affaan-m/ECC

All 673 skills in this repo
  • Skill Stocktake

    affaan-m/ECC

    Audits your installed Claude skills and commands for quality, with a quick mode for recently changed skills and a full mode that evaluates all of them through subagents.

    276k GitHub starsUsed in 5 repos~1.9k tokens
    Auto-check passed
  • Ingests, indexes, searches, edits and monitors video, audio and live streams through the VideoDB Python SDK, returning stream links, clips and timestamps.

    276k GitHub starsUsed in 3 repos~3.5k tokens
    Auto-check: notes
  • Rules Distillation

    affaan-m/ECC

    Scans installed skills for principles that recur across them and proposes rule-file changes: append, revise, add a section, create a file or leave as covered.

    276k GitHub starsUsed in 2 repos~2.3k tokens
    Auto-check passed
  • Builds DRAFT counterparty agreements from one markdown template and a small JSON spec per party, with clauses picked by the party's role.

    276k GitHub stars~2.9k tokensUpdated 4 days ago
    Auto-check passed
  • Measures whether agents actually follow a skill, rule or agent definition by generating scenarios at three strictness levels and scoring tool-call traces.

    276k GitHub starsUsed in 1 repo~623 tokens
    Auto-check passed
  • Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.

    276k GitHub stars~3.5k tokensUpdated 4 days ago
    Auto-check passed

Works with

Categories

Questions about Backend Patterns

What does Backend Patterns do?

Patrones de arquitectura backend, diseño de API, optimización de base de datos y buenas prácticas del lado del servidor para Node.js, Express y rutas API de Next.js. Backend Patterns is an agent skill from affaan-m/ECC.js.

When should I use Backend Patterns?

Backend Patterns fits situations like: tasks that involve Backend development.

How do I install Backend Patterns in Claude Code?

Run `npx skills add affaan-m/ECC --skill backend-patterns -a claude-code`. Or copy the skill folder (docs/es/skills/backend-patterns in affaan-m/ECC) into .claude/skills/backend-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Backend Patterns in Codex?

Run `npx skills add affaan-m/ECC --skill backend-patterns -a codex`. Or copy the skill folder (docs/es/skills/backend-patterns in affaan-m/ECC) into .agents/skills/backend-patterns in your project. Codex loads it when a task matches its description.

Can I use Backend Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add affaan-m/ECC --skill backend-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/backend-patterns, .gemini/skills/backend-patterns, .github/skills/backend-patterns and .opencode/skills/backend-patterns in your project.

What does Backend Patterns need to run?

Going by SKILL.md and its folder, Backend Patterns needs credentials named JWT_SECRET. Our summary lists: Node.js; A credential in JWT_SECRET.

Does Backend Patterns access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Backend Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Backend Patterns use?

Backend Patterns is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Backend Patterns use?

About 3.4k tokens (SKILL.md is roughly 14k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Backend Patterns?

Skills that share tags, products or a category with Backend Patterns: Backend Patterns (hellangleZ/burn-in-cceverywhere-ralph, 112 stars), PayRam Checkout Integration (PayRam/payram-mcp, 158 stars), Fullstack Dev (HHU3637kr/skills, 145 stars) and Backend Patterns (xu-xiang/everything-claude-code-zh, 2k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Backend Patterns?

affaan-m (a GitHub user) maintains it in affaan-m/ECC, which has 275,546 GitHub stars. The repository holds 673 skills in this directory. The repository was last updated on October 5, 2026.

Source: affaan-m/ECC on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.