---
name: software-engineering
description: Use when designing a system or service, choosing an architecture, writing a design doc or ADR, reviewing code or a pull request, planning a test strategy, designing an API or a database schema, planning a migration, setting up CI/CD, adding observability, hardening security, or refactoring for maintainability. Triggers - "design a system for", "how should I structure this", "review this PR", "is this a good architecture", monolith versus microservices, REST API design, schema or data migration, "what tests do we need", "make this production ready", tech debt.
---

# Software Engineering

Every design choice trades something for something else. The work is to make the
trade explicit against the real requirements and then pick the simplest design
that meets them. Simplicity is the default because every added component must be
understood, deployed, monitored and debugged for as long as the system lives.

**In an existing codebase, its conventions come first.** Read how it handles
errors, configuration, tests and layering before proposing anything, and follow
that unless the task is to change it.

## Designing something

1. **Requirements as numbers.** Users, requests per second, data size and growth,
   latency target, availability target, consistency needs, team size. If they are
   unknown, state the assumption; a design without numbers cannot be wrong, and
   so cannot be right.
2. **Constraints.** Existing stack, skills, budget, deadline, compliance.
3. **Two or three real options**, each with what it costs and what it risks.
   Include the boring one.
4. **Decide and say why**, naming what was given up.
5. **Write it down** as a short design doc or ADR (`references/design-docs.md`).
6. **Plan the first slice**: the thinnest end-to-end path that proves the risky part.

## Choosing an architecture

| Style | Fits when | Costs |
|---|---|---|
| Monolith with clear modules | one team, one product, unknown boundaries | discipline to keep modules separate |
| Services | several teams needing independent deploys or very different scaling | network failures, distributed data, operational load |
| Event-driven | producers must not wait for consumers; many consumers of the same fact | eventual consistency, harder debugging, ordering and duplicates |
| CQRS | read and write shapes or loads differ greatly | two models to keep in step |
| Serverless functions | spiky or low traffic, small units of work | cold starts, limits, harder local testing |

Start with a modular monolith unless a named requirement rules it out. Splitting
a well-structured monolith later is routine. Merging badly drawn services is not.
Draw boundaries around things that change together, and put a transaction's data
on one side of a boundary.

## Principles, and when they are overdone

| Principle | Buys | Overdone when |
|---|---|---|
| Single responsibility | a module changes for one reason | classes so small the logic is scattered across ten files |
| Depend on abstractions | swappable, testable edges | an interface with exactly one implementation and no test double |
| Don't repeat yourself | one place to fix a rule | unrelated code forced to share because it looked alike |
| Open for extension | new cases without editing old code | plugin machinery for a case that never arrives |
| You aren't gonna need it | less code to carry | used to skip things known to be needed (auth, migrations, logs) |

Duplication is cheaper than the wrong abstraction. Wait for the third occurrence.

## Code that stays maintainable

- Names say what a thing is for. If a comment is needed to explain a name, rename it.
- Functions do one thing at one level of abstraction; guard clauses over nesting.
- Keep side effects (I/O, time, randomness) at the edges and the logic in pure
  functions between them. That one habit makes most code testable.
- Make invalid states impossible to construct rather than checking for them everywhere.
- Comments explain why, and what was tried and rejected. The code says what.
- Delete dead code. Version control remembers it.

## Reliability

- Every network call has a timeout. Retries use exponential backoff with jitter
  and a cap, and only for operations that are safe to repeat.
- Make writes idempotent (idempotency key or natural key) so a retry cannot
  double-charge or double-send.
- Bound every queue and pool, and decide what happens when it is full.
- Fail fast at startup on bad configuration, not on the first request.
- Design the rollback before the rollout: feature flag, backward-compatible
  schema change, previous version still deployable.

## Testing

| Layer | Proves | Share |
|---|---|---|
| Unit | a rule or calculation is right; fast, no I/O | most |
| Integration | the code works with the real database, queue or API contract | some |
| End to end | a critical user journey works when everything is wired up | few |

Test behaviour through public interfaces so refactoring does not break tests.
Cover the unhappy paths: invalid input, timeouts, duplicates, partial failure. A
bug fix starts with a failing test. Coverage is a way to find untested code, not
a target that shows the tests are good.

## Reviewing code

Review in this order, and stop to raise a blocking issue before polishing below it:

1. **Does it do the right thing?** Requirements, edge cases, failure paths.
2. **Is it safe?** Input validation, authorization, secrets, injection, data loss.
3. **Will it hold up?** Concurrency, timeouts, queries in loops, unbounded growth.
4. **Can the next person change it?** Structure, names, tests that explain intent.
5. **Style**, only where the linter does not already decide.

Say what is wrong, why it matters and what would fix it. Mark each comment as
blocking, suggestion or question. Point out what is good too; it tells the
author what to keep doing. Full checklist in `references/review-checklist.md`.

## Security baseline

- Validate and bound all input at the boundary; encode output for its context.
- Parameterised queries only. Never build SQL, shell commands or paths from input.
- Authenticate, then authorize every request on the server, per object.
- Secrets live in a secret manager or the environment, never in the repository.
- Least privilege for services, databases and tokens. Pin and audit dependencies.
- Log security events, and keep credentials and personal data out of logs.

## Operability

Emit structured logs with a request or correlation id, metrics for rate, errors
and duration on every endpoint, and traces across service calls. Alert on
symptoms users feel (error rate, latency against the target), not on every
cause. Every alert links to a runbook.

## References

| File | When |
|---|---|
| `references/design-docs.md` | design doc and ADR templates, back-of-envelope capacity estimates |
| `references/api-and-data.md` | REST conventions, error format, pagination, versioning, schema design, zero-downtime migrations |
| `references/review-checklist.md` | detailed pull request, security and release checklists |
