Backend patterns
Use when writing or reviewing server-side code behind an endpoint — data access, service layers, database queries, caching, transactions, background work, auth enforcement, or logging. Also use when a query is slow, when a list endpoint loads related records in a loop, when deciding whether logic belongs in the handler, and when reaching for a queue or a cache.From its SKILL.md
npx -y skills add m-de-graaff/skills --skill backend-patternsAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
9.5 KB, as published. Nobody here has run it
Backend Patterns
What happens after the request is parsed and before the response is shaped. The wire contract —
URLs, status codes, response bodies — is api-design.
Core principle: the handler is the thinnest layer. It parses, calls one thing, and formats. Business logic in a handler cannot be tested without HTTP and cannot be reused by a job, a CLI, or the next endpoint.
Layers
handler parse, authorize, call service, format response
service business logic, orchestration, transactions
repository data access — the only layer that knows about the database
Introduce a layer when it earns its place, not on principle. A repository with one caller and no second implementation is indirection; a service with no logic beyond forwarding to the repository is a file you'll open and close for years.
The signal to split: a second caller appears, or you want to test the logic without a database.
class MarketService {
constructor(private markets: MarketRepository) {}
async search(query: string, limit = 10): Promise<Market[]> {
const embedding = await generateEmbedding(query);
const hits = await this.markets.vectorSearch(embedding, limit);
const scores = new Map(hits.map(h => [h.id, h.score]));
const found = await this.markets.findByIds(hits.map(h => h.id));
return found.sort((a, b) => (scores.get(b.id) ?? 0) - (scores.get(a.id) ?? 0));
}
}
The handler for that is three lines. That's the point.
Queries
Select the columns you need. SELECT * ships every column over the wire, defeats
covering indexes, and silently changes shape when someone adds a TEXT column.
N+1 is the default failure mode, and it hides well — it's fast on the ten rows you tested with and catastrophic on a thousand.
// N+1: one query, then one per row
const markets = await getMarkets();
for (const m of markets) m.creator = await getUser(m.creatorId);
// Two queries, regardless of row count
const markets = await getMarkets();
const creators = await getUsers(markets.map(m => m.creatorId));
const byId = new Map(creators.map(c => [c.id, c]));
for (const m of markets) m.creator = byId.get(m.creatorId);
Watch for the version that hides inside an ORM: a lazy relation accessed in a map, or a
serializer that resolves an association per record. Log queries in development and count them
for one request — the number should not scale with the result set.
Every column you filter, sort, or join on needs an index. Confirm with EXPLAIN; a
sequential scan on a growing table is a future incident with a date on it.
Transactions
Wrap writes that must all land or none. The boundary belongs in the service layer — the repository shouldn't decide what's atomic.
await db.transaction(async tx => {
const order = await orders.create(tx, data);
await inventory.decrement(tx, data.items);
return order;
});
Do nothing non-transactional inside one. No HTTP calls, no queue publishes, no emails — those can't roll back, and holding a transaction open across a network call is how connection pools get exhausted. Collect the side effects and fire them after commit.
Caching
Cache when you've measured that something is slow and the data tolerates being stale. Caching an already-fast query buys you a second source of truth and a class of bug where the fix works locally and not in production.
async function getMarket(id: string): Promise<Market> {
const key = `market:${id}`;
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
const market = await db.markets.findUnique({ where: { id } });
if (!market) throw new NotFoundError(`market ${id}`);
await redis.setex(key, 300, JSON.stringify(market));
return market;
}
Decide invalidation before you add the cache. Every write path that touches the entity must delete the key, and a TTL is the backstop for the path you forget — not the strategy.
Caching a QUERY response means keying on the body. RFC 10008 makes QUERY cacheable, and the
cache key MUST incorporate the request content — a key derived from the URL alone serves one
query's results for every other query to that endpoint. Hash the canonicalised body into the key,
and canonicalise deliberately: if {"a":1,"b":2} and {"b":2,"a":1} should hit the same entry,
something has to sort the keys. See api-design for the method's semantics.
Cache in-process only for data that is identical across replicas and cheap to lose: compiled regexes, parsed config, a feature-flag snapshot. Per-request or per-user data in a process-local map is a bug on the second replica.
Background work
Use the platform's queue. BullMQ, SQS, Cloud Tasks, pg-boss, whatever the deployment
already runs. An in-process array is not a queue — it loses everything on deploy, doesn't retry,
doesn't survive a crash, and doesn't exist on the other replica that received the follow-up
request.
What the queue must give you, and what you have to build yourself if you hand-roll it: durable storage, retry with backoff, a dead-letter path, idempotent handlers, and visibility into what's stuck.
Handlers must be idempotent. At-least-once delivery is the norm, so a job that charges a card must be safe to run twice — key it on the operation, not the invocation.
The only case for an in-process queue: fire-and-forget work you would be content to lose, in a single-process app. Say that in a comment where you build it.
Errors
Map domain failures to transport at the edge. The service layer throws domain errors and knows nothing about HTTP; one handler translates.
export function toResponse(error: unknown): Response {
if (error instanceof ValidationError) return json(422, "validation_error", error.message, error.fields);
if (error instanceof NotFoundError) return json(404, "not_found", error.message);
if (error instanceof ConflictError) return json(409, error.code, error.message);
if (error instanceof ForbiddenError) return json(403, "forbidden", "Not permitted");
logger.error({ err: error }, "unhandled error");
return json(500, "internal_error", "Internal server error");
}
Never let an unrecognised error's message reach the client. Driver errors leak table names,
column names, and sometimes values. The response shape itself is api-design's.
Retry only what's idempotent and only what's transient — a network blip or a 503, with exponential backoff and a cap. Retrying a 400 just makes the same mistake four times, and retrying a non-idempotent POST creates four orders.
Auth
Authentication says who; authorization says whether. Authorization is per-resource, and the check that gets forgotten is ownership:
const order = await orders.findById(id);
if (!order) throw new NotFoundError("order");
if (order.userId !== user.id) throw new NotFoundError("order"); // not 403 — don't confirm it exists
Middleware can enforce "is authenticated" and "has role admin". It cannot enforce "owns this row", so that check lives beside the fetch — and returning 404 rather than 403 avoids confirming the resource exists to someone who shouldn't know.
Logging
Use the ecosystem's structured logger — pino, zap, structlog — configured once. A hand-rolled
Logger class wrapping console.log gets you JSON and nothing else: no levels at runtime, no
redaction, no sampling, no child loggers, no transport.
What matters is what you put in it: a request ID on every line, the user ID, the operation, and the duration. Never the token, the password, the card number, or the whole request body.
logger.info({ requestId, userId, route: "GET /api/v1/markets", ms: 42, count: 20 }, "markets listed");
Log at the boundaries — request in, response out, external call, error — not at every step inside. Logs that narrate control flow are the ones nobody reads.
Rate limiting
Use a shared store: Redis, the gateway, or the platform's own limiter. Per-process in-memory counters reset on deploy, split across replicas, and fail open under exactly the serverless and autoscaling conditions where you need them.
The headers and the 429 body are api-design's.
Checklist
- Handler is thin — parse, authorize, delegate, format
- No
SELECT *on a path that runs often - Query count per request doesn't scale with the number of rows returned
- Filtered, sorted, and joined columns are indexed, confirmed with
EXPLAIN - Transactions contain no network calls
- Every cache has a named invalidation path, not just a TTL
- Background jobs are durable and idempotent
- Domain errors mapped at one place; nothing unrecognised reaches the client
- Ownership checked next to the fetch, not only in middleware
- Logs are structured, carry a request ID, and contain no secrets
- Rate limiting uses a shared store
Non-goals
Doesn't design the HTTP contract (api-design). Doesn't cover frontend, infrastructure, or
deployment. Doesn't audit for vulnerabilities — that's /security-review.
Source
Adapted from ECC by Affaan Mohamed (MIT).