agentleFS
davidbzdavidbz/production-engineering-skills/skills/production-engineering/SKILL.md

production-engineering

Skill0 starsChanged 4 months agoMITView on GitHub

Engineering standards for writing production-grade backend and service code in any language. Use this skill whenever writing, reviewing, or refactoring server-side code (services, APIs, workers, handlers, business logic, data access layers, or microservices), even if the user doesn't explicitly ask for "production quality." Also use when the user asks for code review, asks to "harden" code, or mentions cloud-native, Kubernetes, multi-tenant, or distributed systems. Covers data-oriented design, error handling, input sanitization, IO limits, observability (logs/metrics/traces), testability, statelessness, multi-tenancy, and the division of responsibility between application code and platform (service mesh / DevOps).

2 other projects use a version of this.

Adopted by

Most recently taken up by

  • Other versions2 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 2

    1. ghanendrasahu/production-engineering★ 0same name
    2. ios3kov/codex-skills★ 0same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

The file

Show its rules and text

We split this skill into the rules it gives an agent

25 rules. About 0 are common, 20 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈20

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Never store request data, entities, or intermediate results as members.

    line 20
  2. Very specific:

    No magic numbers: Every literal with meaning becomes a named constant (maxRetries = 3, defaultPageSize = 100), defined once near the top or …

    line 53
  3. Very specific:

    No redundant comments: Never comment what the code already says (i++ // increment i).

    line 55
  4. Distinctive:

    Treat every input as hostile: HTTP bodies, headers, query params, queue messages, file uploads, and data read back from shared storage.

    line 67
  5. Distinctive:

    Use parameterized queries.

    line 71
  6. Distinctive:

    After validation, pass typed, validated objects inward.

    line 73
  7. Distinctive:

    Never read an unbounded amount of anything into memory.

    line 77
  8. Distinctive:

    If the expected size is known (Content-Length, schema), verify it fits the limit before allocating, then pre-allocate exactly what's needed.

    line 80
  9. Distinctive:

    Every network call gets a timeout and a context/cancellation token.

    line 82
  10. Very specific:

    Always structured (JSON or the platform's structured format), never printf prose.

    line 86
  11. Very specific:

    Every entry includes: timestamp, level, service name, event name, trace_id/request_id, and tenant_id when in a request context.

    line 87
  12. Distinctive:

    Never log secrets, tokens, passwords, full payloads, or raw PII.

    line 89
  13. Distinctive:

    Use OpenTelemetry (the industry standard) or the codebase's existing equivalent.

    line 95
  14. Distinctive:

    Every collection, buffer, queue, cache, pool, and string in the system has an explicit maximum, enforced in code:

    line 111
  15. Distinctive:

    When a limit is hit, fail fast with a clear error, don't degrade silently.

    line 119
  16. Distinctive:

    All environment specifics come from config (env vars / config files / flags) read once at startup into a typed config object, validated at …

    line 125
  17. Distinctive:

    No imports of orchestrator APIs in business logic.

    line 127
  18. Distinctive:

    No state in memory between requests: no session maps, no "current user", no local counters that matter, no local files as a source of truth.

    line 134
  19. Very specific:

    All shared state goes to shared storage: Redis/DB/object storage.

    line 135
  20. Distinctive:

    No state change: no DB writes, no queue publishes, no cache mutations, not even "last seen" updates.

    line 148
  21. Distinctive:

    Every piece of persisted data is scoped to a tenant, always:

    line 158
  22. Distinctive:

    All time in the system is UTC, at millisecond precision, everywhere.

    line 176
  23. Distinctive:

    Never read the server's local timezone.

    line 182
  24. Distinctive:

    When writing new code: follow all sections. Wire dependencies in main/composition root.

    line 188
  25. Distinctive:

    When reviewing code: check sections 1-16 in order and report violations with the section number, why it matters, and a concrete fix.

    line 194

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Production Engineering Standards

These are the house rules for all service-side code. Apply them in every language. When an existing codebase conflicts with a rule, follow the codebase's convention and flag the difference to the user rather than silently rewriting.

The core philosophy: application code contains business logic and nothing else. Infrastructure concerns (TLS, circuit breaking, retries at the network layer, service discovery) belong to the platform. State belongs to shared storage. The app is a stateless, runtime-agnostic function from sanitized input to output, wrapped in observability.

1. Data-oriented design: separate data from code

Data structures are plain and dumb: fields only, no behavior. Logic lives in separate components that receive data as arguments.

A business-logic component may hold as members only:

  • other business-logic collaborators (interfaces/function dependencies), and
  • configuration (immutable after construction).

Never store request data, entities, or intermediate results as members. Pass them through function parameters. If a struct/class mixes data fields with logic dependencies, split it.

// GOOD: plain data           // GOOD: logic holds only deps + config
type Order struct {           type OrderService struct {
    ID       string               repo    OrderRepo      // collaborator
    TenantID string               clock   func() time.Time
    Amount   int64                cfg     OrderConfig    // config
}                             }
                              func (s *OrderService) Place(ctx, o Order) error { ... }

// BAD: logic object carrying data
type OrderService struct { currentOrder Order; db *sql.DB }

Why: instances can be shared safely across goroutines/threads/requests, tested trivially, and scaled horizontally without hidden coupling.

2. Control flow: return early, stay flat, stay simple

Handle failures, guards, and edge cases first and return immediately. The happy path reads top-to-bottom at minimal indentation.

  • Avoid else as much as possible. No else after a returning if. When a variable's value depends on a condition, initialize it with the default and override with an if, instead of if/else branching:
// Avoid:                          // Prefer:
if inv.PaidAt != nil {             status := "pending"        // default
    status = "paid"                if inv.PaidAt != nil {
} else {                               status = "paid"        // override
    status = "pending"             }
}
  • Avoid engineering complexity. Deep nesting (3+ levels of if) means invert conditions or extract a function. Long functions (roughly a screen, ~40 lines) mean extract well-named helpers. One function, one job.
  • No magic numbers. Every literal with meaning becomes a named constant (maxRetries = 3, defaultPageSize = 100), defined once near the top or in config (see section 9). The name states what the number means.
  • No emojis in code, comments, logs, commit messages, or API responses.
  • No redundant comments. Never comment what the code already says (i++ // increment i). Comment only the why: non-obvious decisions, workarounds, invariants. If code needs a "what" comment, rename or extract instead.

3. Error handling

  • Handle or propagate every error. Never swallow one silently; if intentionally ignored, say why in a comment and log it.
  • Wrap errors with context as they travel up (fetch order {id}: {cause}), preserving the original cause for logs.
  • Never expose internals to callers. External responses get a stable error code, a safe generic message, and a correlation/request ID. Stack traces, SQL, file paths, internal hostnames, and library error strings go to structured logs only.
  • Panics/uncaught exceptions are recovered once, at the edge middleware: log with stack trace, return a generic 500, keep the instance alive. Never panic or throw for control flow in business logic; a panic reaching the edge is a bug.
  • Map internal errors to a small, documented set of external error types (invalid_input, not_found, conflict, rate_limited, internal). Distinguish caller errors (4xx, don't retry) from system errors (5xx, retryable).

4. Sanitize all incoming data

Treat every input as hostile: HTTP bodies, headers, query params, queue messages, file uploads, and data read back from shared storage.

  • Validate at the edge, immediately after decode, before any logic runs. Reject, don't fix.
  • Enforce schema (types, required fields), bounds (lengths, ranges, formats), and allowlists for enums.
  • Use parameterized queries; never build queries/commands from string concatenation.
  • Canonicalize and validate paths, URLs, and identifiers (no .., no unexpected schemes).
  • After validation, pass typed, validated objects inward. Inner layers should never see raw input.

5. Bounded IO: limit and stream

Never read an unbounded amount of anything into memory.

  • Cap request/message body size at the edge (e.g., HTTP MaxBytesReader-style limits, gRPC max message size). If input is compressed, the limit applies to decompressed bytes too (wrap the decompressor in a limited reader), or a small gzip bomb defeats the cap.
  • If the expected size is known (Content-Length, schema), verify it fits the limit before allocating, then pre-allocate exactly what's needed.
  • Stream anything potentially large: uploads to object storage, downloads, exports, DB result sets (cursor/pagination, never unbounded SELECT *), file processing (chunked reads).
  • Every network call gets a timeout and a context/cancellation token. No infinite waits.

6. Structured logs

  • Always structured (JSON or the platform's structured format), never printf prose.
  • Every entry includes: timestamp, level, service name, event name, trace_id/request_id, and tenant_id when in a request context.
  • Log decisions and state transitions with the data needed to debug them (ids, counts, durations), not "entered function X".
  • Never log secrets, tokens, passwords, full payloads, or raw PII. Log identifiers instead.
  • Levels mean something: ERROR = a human should look, WARN = degraded but self-handled, INFO = state transitions and decisions, DEBUG = development detail (off in prod). Expected occurrences (validation failures, 404s) are not ERROR.
  • Log an error once, at the layer that handles it, not at every propagation hop.

7. Metrics and tracing

Use OpenTelemetry (the industry standard) or the codebase's existing equivalent.

  • Metrics on every entry point and every outbound dependency: request count, error count, and latency histogram (the RED trio), plus business counters for key events. Label by operation and route template. Never label by unbounded values (user IDs, raw URLs); label by tenant only when the tenant count is known and bounded (say, under 100). Otherwise put tenant in traces and logs, not metric labels.
  • Tracing: one span per inbound request, child spans for each outbound call (DB, cache, HTTP, queue). Propagate context (W3C traceparent) across every hop, including queue messages. Put the trace ID in every log line.
  • Instrumentation lives in middleware/interceptors and thin client wrappers, not scattered through business logic.

8. Testability: inject third parties as runtime functions

Business logic never calls a third party (DB, HTTP client, clock, RNG, filesystem, queue) directly. It depends on narrow interfaces or injected functions, provided at construction.

  • Define the interface where it's used (the consumer owns it), keep it minimal (1-3 methods).
  • now(), uuid(), rand() are injected functions too. Deterministic tests need deterministic time and IDs.
  • Unit tests replace these with in-memory fakes/stubs. No network, no disk, no sleeps in unit tests.

9. Hard-limit every object

Every collection, buffer, queue, cache, pool, and string in the system has an explicit maximum, enforced in code:

  • Max items per API page / batch / bulk operation.
  • Max field lengths on every input string; max elements on every input array.
  • Bounded in-memory queues and worker pools (backpressure or reject when full, never grow unbounded).
  • Caches with max entries + TTL.
  • Max connections, max concurrent requests. If the app retries anything itself (e.g., a storage op), the attempt count is capped; network-level retries between services belong to the mesh (see section 12).

When a limit is hit, fail fast with a clear error, don't degrade silently. Limits live in config with sane defaults.

10. Runtime-agnostic

Code must not know or care whether it runs in Kubernetes, a container, a VM, or a laptop.

  • All environment specifics come from config (env vars / config files / flags) read once at startup into a typed config object, validated at startup. Fail fast on bad config.
  • Secrets (DB credentials, API keys) come from the environment or a secret store the platform injects. Never hardcoded, never in the repo, never in defaults, and (per section 6) never logged.
  • No imports of orchestrator APIs in business logic; no filesystem-path assumptions; listen address, ports, and dependency endpoints all come from config.
  • Graceful shutdown on SIGTERM (stop accepting, drain in-flight, then exit) and standard liveness/readiness signals. These are the only contract with the runtime, and they live at the edge, not in logic. Liveness answers only "is the process alive" and never checks dependencies; dependency health belongs in readiness. A liveness probe that pings the DB turns a DB blip into a fleet-wide restart storm.

11. Stateless: assume N instances

Any instance may handle any request; any instance may die at any moment.

  • No state in memory between requests: no session maps, no "current user", no local counters that matter, no local files as a source of truth.
  • All shared state goes to shared storage: Redis/DB/object storage. Locks are distributed locks (with TTLs). Scheduled work uses distributed scheduling or leader election via shared storage, never if instance == 0.
  • In-memory caching is allowed only as a read-through optimization with TTL, where stale reads are acceptable.
  • Idempotency: handlers that mutate state accept an idempotency key stored in shared storage, since retries and duplicate deliveries are guaranteed to happen.

12. What the platform owns (don't build it in the app)

  • Circuit breaking, outlier detection, network-level retries, rate limiting at the edge: handled by the service mesh / proxy (Envoy, Istio, etc.). Do not implement circuit breakers in application code. The app's job is to time out promptly, return clear error codes, and stay idempotent so the mesh's retries are safe.
  • Transport security: TLS versions, cipher suites, mTLS between services, and cert rotation are owned by DevOps/the mesh. Application code serves plain HTTP / insecure gRPC on its local interface and never touches certificates or TLS config. Trust that the platform wraps all traffic; never hardcode https:// assumptions or TLS settings in app code. (Flag to the user if a service is exposed without such a platform layer; then this rule doesn't apply.)

13. Unauthorized requests are cheap and inert

Authentication (who is calling) is checked first, before anything else, and needs no IO beyond the token/session check itself. Authorization (may they do this) is checked as early as possible; when it requires loading the target resource (ownership checks), that single tenant-scoped read is allowed, and it happens before any mutation or expensive work. A request that fails either check must cause:

  • No state change: no DB writes, no queue publishes, no cache mutations, not even "last seen" updates.
  • No config change: nothing about the system's behavior shifts.
  • No significant resource use: auth check happens before body parsing, before DB lookups, before any expensive work. The reject path allocates almost nothing; secret/token comparisons use constant-time compare to avoid timing attacks.

Order of a handler: size limit, then auth, then decode, then validate/sanitize, then business logic, then respond.

Exception: signature-based auth (HMAC-signed webhooks) requires reading the body to authenticate. There, the order is size limit, bounded body read, verify signature, then decode, and still nothing else happens before verification succeeds.

14. Multi-tenant data segmentation

Every piece of persisted data is scoped to a tenant, always:

  • Key-value / Redis: prefix every key with the tenant ID ({tenant_id}:orders:{order_id}).
  • SQL/NoSQL: a tenant_id column/field on every table/collection, present in every WHERE clause and every unique index. Never query without it.
  • Object storage: tenant ID in the object path prefix.
  • The tenant ID comes from the authenticated context, never from user-supplied body fields, and is threaded through the call chain (context object), so a missing tenant is a programming error caught loudly.
  • Where the language allows, make IDs distinct types (TenantID, OrderID newtypes/wrappers), not bare strings. With bare strings, swapping two ID arguments compiles cleanly and leaks data across tenants; with typed IDs it's a compile error.

15. Unit tests

  • Bug fixes are test-first. Reproduce the bug with a new test, run it, and confirm it fails for the expected reason. Only then apply the fix and watch the test pass. The test stays in the suite as a regression guard. A fix without a failing-first test doesn't prove the bug was understood.
  • Cover the important flows: happy path, each validation failure, each dependency failure, limit/boundary conditions, and tenant isolation.
  • Target 85%+ line coverage on business-logic packages (generated code, plain data structs, and main/wiring excluded). Coverage is a floor, not the goal: assert behavior, not implementation.
  • Structure: table-driven/parameterized where natural; Arrange-Act-Assert; fakes injected per section 8; deterministic (injected clock/IDs, no sleeps, no network).
  • Include at least one test proving internal errors are not leaked to the caller, and one proving unauthorized requests cause no state change.

16. Time discipline: UTC, millisecond precision

All time in the system is UTC, at millisecond precision, everywhere.

  • Store, compute, compare, and serialize timestamps in UTC only. Convert to a local timezone solely at the display edge (UI/report rendering), never in logic or storage.
  • Wire format: epoch milliseconds (integer) or RFC 3339 with milliseconds and the Z suffix (2026-08-18T09:30:00.123Z). Pick one per API and use it consistently. No naive (timezone-less) timestamps ever cross a boundary.
  • Storage: timezone-aware UTC column types (e.g., timestamptz in Postgres) with millisecond precision; epoch millis for Redis/queue payloads. Never store local time, never store a timezone-less string.
  • The injected now() (section 8) returns UTC, truncated/rounded to milliseconds, so serialized values round-trip exactly and tests compare cleanly.
  • Never read the server's local timezone; the runtime's TZ setting must not affect behavior (see section 10).
  • Durations are measured with a monotonic clock, never by subtracting two wall-clock readings (NTP steps and leap seconds make wall-clock deltas lie).
  • Log timestamps and trace timestamps: UTC with milliseconds, same rule.

How to apply this skill

When writing new code: follow all sections. Wire dependencies in main/composition root; keep handlers thin (size limit, auth, decode, validate, call service, map errors, respond, per section 13).

Proportionality: full rigor applies to services and long-lived code. For one-off scripts, prototypes, or exercises, keep the free habits (early returns, error handling, no hardcoded secrets, bounded reads) and skip the ceremony (OTel, idempotency keys, coverage targets), and say so in one line when doing it.

When fixing bugs: per section 15, write the reproducing test first, confirm it fails, then fix.

When reviewing code: check sections 1-16 in order and report violations with the section number, why it matters, and a concrete fix.

When the user's requirements conflict (e.g., they want TLS in-app, or in-memory sessions): do what they ask, but note which house rule it breaks and the tradeoff, in one sentence.

For fuller code examples of these patterns (Go, Python, TypeScript), read references/patterns.md.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.