Catalogue / server-side-engineering
server-side-engineering
Older skill: source not recordedSignedGuides the design, implementation, review, and repair of production-quality backend services. Covers choosing languages, frameworks, and databases; designing REST, GraphQL, and gRPC interfaces; securing authentication, authorization, and input handling; tuning queries, caching, and scaling; structur…--- name: server-side-engineering description: > Guides the design, implementation, review, and repair of production-quality backend services. Covers choosing languages, frameworks, and databases; designing REST, GraphQL, and gRPC interfaces; securing authentication, authorization, and input handling; tuning queries, caching, and scaling; structuring test suites; and planning safe migrations and deployments. Use when the user asks to build or review a server-side system, design or version an API, implement login, roles, or tokens, fix a slow query or endpoint, add caching or queues, write backend tests, pick a database, or prepare a release pipeline. Not for frontend or mobile UI work, ML model training, standalone infrastructure provisioning, or general coding help with no server component. ---
Server-Side Engineering
You are helping design, build, review, or debug the server side of an application. Work through the phases below in order, adapting depth to the size of the task: a one-endpoint fix needs a sentence of reasoning, a greenfield system needs all ten phases. Always state the trade-off you are accepting, not just the choice you made.
Phase 1 — Scope the Problem Before Writing Code
Answer these in your head (or out loud for large tasks) before proposing anything:
- What is the core domain? Name the entities and their lifecycle (e.g., a venue publishes events, an event sells tickets, a ticket belongs to an attendee).
- What are the non-functional demands: expected reads vs writes, latency targets, consistency needs, team size?
- What are the constraints: existing stack, hosting budget, compliance rules?
Reasoning: most bad backend decisions come from guessing at load or domain shape. If the user has not told you, ask about read/write ratio and consistency requirements before choosing a database or an architecture.
Phase 2 — Choose the Stack
Use this table as a starting point, then justify deviations:
| Situation | Reasonable default | Why | |---|---|---| | Team already writes TypeScript, needs real-time features | Node.js with NestJS or Fastify | One language across the stack, mature WebSocket support | | Service wraps ML models or data pipelines | Python with FastAPI | Native interop with the data ecosystem, async I/O | | Many concurrent connections, small services, CLI tooling | Go with Gin or Echo | Cheap goroutines, single-binary deploys | | Hard latency/memory requirements | Rust with Axum | No GC pauses, memory safety at low level | | Money, inventory, or any multi-step transaction | PostgreSQL | ACID guarantees, rich constraints and window functions | | Rapidly varying document shapes (catalogs, CMS content) | MongoDB | Schema flexibility, built-in horizontal sharding | | Sub-millisecond lookups, sessions, rate counters | Redis | In-memory data structures with persistence options | | Background jobs at modest scale | RabbitMQ | Routing, acknowledgments, dead-letter queues | | High-volume event streams with replay | Kafka | Durable log, consumer groups, millions of messages per second |
Default guidance: when nothing pushes you elsewhere, pick PostgreSQL, one application process, and a boring framework. Start with a modular monolith; extract services only after a boundary proves itself (Phase 7).
Phase 3 — Design the Contract First
REST resources
Model URLs around nouns, not verbs. For a ticketing API:
GET /api/v1/events list events (paginated)
POST /api/v1/events create event
GET /api/v1/events/{id} fetch one event
PATCH /api/v1/events/{id} partial update
DELETE /api/v1/events/{id} cancel event
GET /api/v1/events/{id}/tickets nested collection
POST /api/v1/events/{id}/tickets purchase ticketReject verb-in-path designs (anything like a "getEvent" or "cancelTicket" URL); if an action does not map to CRUD, give it a sub-resource (for example, a reservation resource created under a ticket).
Status codes
Return the most specific code that fits:
| Code | Use it when | |---|---| | 200 | Successful read or update | | 201 | Resource created; include a Location header | | 204 | Successful delete or empty response | | 400 | Malformed request the client must fix | | 401 | No or invalid credentials | | 403 | Valid credentials, insufficient permission | | 404 | Unknown resource (also use for resources the caller may not know exists) | | 409 | Conflicting state, e.g., seat already held | | 422 | Well-formed request that fails semantic validation | | 429 | Rate limit exceeded, with Retry-After | | 503 | Dependency down or not ready |
Error envelope
Use one consistent error shape everywhere, and never leak stack traces, SQL text, or server versions in it:
{
"error": {
"code": "SEAT_UNAVAILABLE",
"message": "Seat 14B is no longer available for this event",
"field": "seatId",
"requestId": "req_8f2a91",
"occurredAt": "2026-03-04T10:12:00Z"
}
}Include a request identifier so support can correlate with logs.
Pagination, filtering, sorting
Default to cursor pagination for public collections (offsets degrade on large tables and allow duplicates during concurrent inserts):
GET /api/v1/events?venueId=42&status=scheduled&sort=-startsAt,title&limit=25
Response carries data, a nextCursor, and hasMore. Cap the page size (for example, refuse anything over 100) so a client cannot request the whole table.
Versioning
Prefer a URL segment (/api/v1/) because it is cache-friendly and visible in logs. Treat a version as frozen once released: add fields, never remove or repurpose them; a breaking change means a new version plus a published deprecation date.
GraphQL
Reach for GraphQL when clients genuinely need to shape their own responses (many different frontends over one graph). Sketch the schema first:
type Event {
id: ID!
title: String!
startsAt: DateTime!
venue: Venue!
ticketsRemaining: Int!
}
type Query {
event(id: ID!): Event
events(venueId: ID, first: Int = 25, after: String): EventConnection!
}
type Mutation {
reserveSeat(input: ReserveSeatInput!): Reservation!
}Two non-negotiables: batch nested lookups (a per-parent query loop is the classic resolver performance trap — use a batching utility that groups keys into one query), and cap query depth and complexity so a client cannot request an arbitrarily deep tree.
gRPC
Use protobuf-defined services for internal service-to-service calls where you control both ends and want typed contracts and streaming. Keep the proto file as the single source of truth, generate clients from it, and version by adding optional fields only. For browser consumers, expect to add a translation gateway.
Choosing the style
| Need | Pick | |---|---| | Public, cacheable, wide-audience API | REST | | Many clients with divergent data needs | GraphQL | | Internal, latency-sensitive, typed | gRPC | | Browser push updates | REST plus SSE or WebSockets |
Phase 4 — Model the Data
- Draw entities and relationships before writing migrations. State which invariants the database itself will enforce (unique constraints, foreign keys, check constraints) rather than leaving them to application code — the database is the last line of defense.
- Index for your query patterns, not for every column. A composite index matches a query's filter and sort:
CREATE INDEX idx_tickets_event_created ON tickets (event_id, created_at DESC);
This turns "latest 20 tickets for an event" from a full scan into an index range read. Skip indexes on tiny tables, low-cardinality booleans, and columns rewritten on every update — each index taxes writes.
- Verify with the query planner before and after: read the execution plan, look for sequential scans on large tables and row estimates far from reality.
- Pool database connections. Size the pool from core count (roughly two to four connections per core as a starting point), set an acquire timeout, and guarantee every checked-out connection is released in a
finallyblock or by querying through the pool directly. A leaked connection under load is a classic outage. - Eliminate per-row query loops: fetch related rows in one query with a join or a batched
WHERE id IN (...), then stitch them together in memory. - Migrations: every migration you write must have a tested down-path or a documented forward-fix, and must be deployable while the previous version is still running (add column, backfill in batches, then switch reads — never rewrite a column in place while it is live).
Confirmation gate: before you generate any migration that removes tables or columns, discards or rewrites data, or before you apply any migration to anything other than a disposable local database, stop and tell the user exactly what will be lost and get an explicit yes. Always present the recovery plan alongside the change.
Phase 5 — Secure by Default
Work through these in order for any new endpoint:
- Authorization on the server. Decide, per route, which role or resource owner may act, and enforce it in the handler or a guard — client-side checks are decoration. Deny when unsure, and log denials.
- Injection. Pass every value that originated outside your process to the database through bind parameters (
WHERE email = $1with a values array) and to the shell through an argument array, never through string building. Describe this rule to the user; do not demonstrate the unsafe form. Validate input against an allow-list of expected fields and types before it touches business logic. - Passwords. Hash with Argon2id (memory cost around 64 MiB, three passes as a floor; bcrypt with a high work factor only where Argon2 is unavailable). Require a minimum length of 12 characters, allow passphrases and all characters, check new passwords against known-breach lists, and skip forced periodic rotation.
- Tokens. For user-facing apps, use the authorization-code flow with PKCE and exact redirect-URI matching. Keep access tokens short-lived (around ten minutes), refresh tokens longer with rotation and reuse detection, sign with an asymmetric algorithm, and validate issuer, audience, and expiry on every request. Keep claims minimal — an identifier and roles, nothing sensitive.
- Sessions and cookies. HttpOnly, Secure, SameSite=Strict; regenerate the session identifier at login and privilege changes; store sessions server-side (Redis works well) so revocation is immediate.
- API keys. For machine clients, issue prefixed keys, store only a hash of each key, attach explicit scopes, and make rotation self-service.
- Rate limits. Tier them: around 5 attempts per minute per account on login, roughly 100 requests per minute for anonymous traffic, and per-key budgets for authenticated clients. Return 429 with a retry hint.
- Headers. Set HSTS, a restrictive content-security-policy, frame denial, and nosniff on every response.
- Secrets. Reference configuration by name (environment variables or a secret manager) and fail fast at startup if one is missing. Never hardcode credential values, never invent plausible-looking keys, and never echo a secret's value into code, comments, logs, or this conversation — refer to it by its variable name only.
- Dependencies. Recommend a lockfile plus automated vulnerability scanning in CI, and pin base image digests.
Phase 6 — Make It Fast Enough
Measure before optimizing, then attack in this order because each step is cheaper than the next:
- Fix query plans (indexes, join counts, row counts returned).
Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 19.4 kB | 2c73a7679566 |
| examples.json | 1.9 kB | acf189a0ab06 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 6 Oct 2026 |
Locking a skill to one version needs Pro.