Backend Documentation Format
Detailed Fumadocs MDX format for module and submodule backend architecture documentation.
Backend Documentation Format
Use this format for every module and submodule backend page. It must describe the real implementation, not the intended design. Verify every claim against current files.
Required Source References
| Source | Required Use |
|---|---|
| Existing Fumadocs module docs | Use local examples such as banners/backend.mdx, banners/feature.mdx, banners/api.mdx, search/backend.mdx, and order module docs if present. |
docs/api doc format.md | Use for API/DTO cross-reference structure. |
| Backend module files | Required for module composition, providers, controllers, services, guards, and exports. |
| Schema files | Required for tables, indexes, constraints, enums, relations, generated IDs, and migrations. |
| Infrastructure packages | Required for Redis, BullMQ, realtime, MongoDB, storage, jobs, and shared utilities. |
| Tests and seed files | Required where behavior depends on fixtures, seed data, or verified test expectations. |
Cross-Document Contract
The backend doc is the implementation source for the API, feature/flows, and TDD docs. It must link outward to those sibling docs, and it must explicitly call out where product rules or algorithm rules are implemented.
Frontmatter
---
title: MODULE_NAME Backend Documentation
description: Backend architecture, data model, services, cache, queues, runtime rules, and operational behavior for MODULE_NAME.
---1. Documentation Evidence
| Area | Files Inspected | Verified Details |
|---|---|---|
| Module wiring | apps/api/src/modules/MODULE_PATH/*.module.ts | Imports, providers, exports, route composition. |
| Controllers | ...controller.ts | Route ownership and thin-controller boundaries. |
| Services | ...service.ts | Business logic, validation, writes, mappings, side effects. |
| DTOs | dto/*.ts | API contracts and validation. |
| Schema | packages/db/src/schema/... | Tables, enums, relations, indexes. |
| Jobs | packages/jobs/src/... | Queue contracts and payloads. |
| Cache | CacheKeyUtil, Redis services | Key construction, TTLs, invalidation. |
2. Backend Scope and Boundaries
Owns
- List each responsibility owned by this module.
- Include admin, public, mobile, internal, worker, and scheduled behavior.
- Include submodule ownership.
Does Not Own
- List boundaries owned by other modules.
- Include external services, shared utilities, auth, cache, analytics, or storage boundaries when relevant.
Source of Truth
| Concern | Source of Truth | Notes |
|---|---|---|
| Runtime state | DB/cache/session table | Explain authority. |
| Identity | Auth/guest identity module | Explain guest/user/admin. |
| Score/timer/result | Backend service | Never trust client-computed values. |
3. Module Composition
Document aggregate and leaf modules.
| Module | Type | Path | Controllers | Providers | Exports | Responsibility |
|---|---|---|---|---|---|---|
MODULEModule | Aggregate | apps/api/src/modules/... | None or list | Providers | Exports | Composes leaf modules. |
SUBMODULEModule | Leaf | apps/api/src/modules/... | Controllers | Services | Services | Owns concrete API/behavior. |
Add a diagram:
4. File and Directory Map
Show the real tree for the module.
apps/api/src/modules/MODULE/
MODULE.module.ts
SUBMODULE/
SUBMODULE.controller.ts
SUBMODULE.service.ts
dto/For each important file:
| File | Purpose | Key Exports | Notes |
|---|---|---|---|
path/to/file.ts | Purpose. | ClassName | Important behavior. |
5. Data Model
5.1 Schema Source
packages/db/src/schema/MODULE/
index.ts
enums.ts
table-name.ts5.2 Tables and Collections
Repeat for every SQL table, Mongo collection, Redis state object, or persisted job payload.
TABLE_OR_COLLECTION_NAME
| Column/Field | Type | Nullable | Default | Index/Constraint | Relation | Notes |
|---|---|---|---|---|---|---|
id | serial or uuid | No | generated | PK | N/A | Explain public vs internal ID. |
Include:
- Primary keys.
- Public IDs.
- Foreign keys and delete behavior.
- Unique constraints.
- Check constraints.
- Indexes.
- Soft-delete fields.
- Created/updated timestamps.
- JSON shapes.
- Money units.
- Timezone behavior.
- Denormalised or cached copies of another table's fields.
5.3 Relationship Diagram
6. Services and Responsibilities
Repeat for every service.
6.x SERVICE_NAME
| Method | Called By | Reads | Writes | Side Effects | Errors |
|---|---|---|---|---|---|
methodName() | Controller/job/service | Tables/cache | Tables/cache | Jobs/events/cache invalidation | Error codes |
Explain:
- Input normalization.
- Validation order.
- Transaction boundaries.
- Idempotency.
- Retry behavior.
- Response mapping.
- Fail-open or fail-closed decisions.
- Logger usage.
7. Runtime Flows
Document every major and minor flow. Each flow needs a sequence diagram and branch notes.
7.x FLOW_NAME
| Step | Code Path | Behavior | Failure Case |
|---|---|---|---|
| 1 | Controller.method | Receives request. | DTO validation error. |
| 2 | Service.method | Applies business rule. | Module error. |
Include:
- Success path.
- Validation failures.
- Permission failures.
- Missing entity.
- Duplicate request.
- Cache miss and cache hit.
- Async enqueue success/failure.
- Race/concurrency behavior.
- Guest vs logged-in branch.
8. Caching
| Cache Key Pattern | Builder | Value | TTL | Invalidation | Caller |
|---|---|---|---|---|---|
module:key:segments | CacheKeyUtil.build(...) | Shape | Seconds | Exact invalidation source | Service |
Explain:
- Deterministic segment order.
- Cache hit behavior.
- Cache miss behavior.
- Serialization shape.
- Invalidation on mutations.
- Failure handling.
9. BullMQ, Schedulers, and Async Work
| Queue | Job | Producer | Processor | Payload | Retry/Backoff | Idempotency |
|---|---|---|---|---|---|---|
QueueName.MODULE | module.job | Service | Processor | Payload type | Attempts | Job ID rule |
Add a diagram if jobs exist:
10. Realtime and Events
| Event | Producer | Room/Target | Payload | Consumer | Reliability Notes |
|---|---|---|---|---|---|
event.name | Service | room:id | Shape | Client/service | Delivery semantics. |
11. Security, Auth, and Abuse Controls
Document:
- Guards.
- Permissions.
- Guest identity.
- Admin identity.
- Rate limits.
- Anti-abuse rules.
- Input normalization.
- Sensitive data redaction.
- Audit logs.
- Fail-closed behavior.
13. Error Handling
| Error Code | HTTP Status | Thrown By | Condition | Client Action |
|---|---|---|---|---|
MODULE_ERROR | 400 | Service.method | Exact condition. | Fix request/retry/login. |
14. Observability
| Signal | Location | Purpose |
|---|---|---|
| Log | Logger in service/processor | Failure and state-change visibility. |
| Metric | Name if present | Operational monitoring. |
| Audit | Table/event if present | Admin/accountability tracking. |
15. Testing and Validation
| Test Type | Files | Coverage |
|---|---|---|
| Unit | *.spec.ts | Service methods and edge cases. |
| Integration | *.int-spec.ts | DB/cache/jobs. |
| E2E | *.e2e-spec.ts | Route contracts. |
| Manual | Commands | Verified behavior. |
Include exact validation commands.
16. Mandatory Backend Deep-Dive Pack
This section is required for every generated backend doc. It exists to prevent shallow backend pages that only list files. The backend doc must explain code flow, data flow, tradeoffs, module boundaries, operational behavior, and failure modes in enough detail that a new engineer can debug the module without rereading the entire codebase first.
16.1 Submodule Coverage Matrix
Every submodule, provider, controller, service, processor, scheduler, repository/helper, mapper, and shared dependency must be represented.
| Unit | Type | Owns | Depends On | Called By | Calls | State Touched | Failure Modes |
|---|---|---|---|---|---|---|---|
ClassName | Controller/service/processor | Responsibility | Dependencies | Routes/jobs/services | Downstream calls | DB/cache/job/event | Errors/logging/retry |
Rules:
- If a file exists in the module directory and affects runtime behavior, it must appear.
- If a provider is imported from another module, document why and what contract is used.
- If a helper is intentionally local instead of shared, document that tradeoff.
16.2 UML and Architecture Diagram Pack
Use the diagrams that fit the module. Do not include diagrams that contradict the code.
| Diagram | Required When | Purpose |
|---|---|---|
| Component diagram | Always | Shows modules, submodules, services, and infrastructure. |
| Class diagram | Always for non-trivial modules | Shows controllers, services, DTOs, processors, and relationships. |
| ER diagram | Any SQL persistence | Shows table relationships, PKs, FKs, and join tables. |
| Collection/document diagram | Any MongoDB persistence | Shows document shape and indexes. |
| Sequence diagram | Every major read/write/action/job flow | Shows call order. |
| Activity diagram | Every complex service method | Shows branches, validation, and side effects. |
| State diagram | Any lifecycle/status/session | Shows allowed transitions. |
| Deployment/runtime diagram | Any Redis/BullMQ/realtime/external dependency | Shows runtime topology. |
| Data lineage diagram | Any multi-step transformation | Shows input to domain object to persistence to response/event. |
Example UML-style class diagram:
Example component diagram:
Example deployment/runtime diagram:
16.3 Code Flow Narrative
For every important service method, write a precise narrative in this order:
- Entry point and caller.
- DTO/command shape.
- Auth/identity assumptions.
- Input normalization.
- Validation order.
- Reads performed.
- Business decisions.
- Writes performed.
- Transactions or lack of transaction.
- Cache behavior.
- Jobs/events/notifications.
- Response mapping.
- Error handling.
- Logs/metrics/audit events.
- Known tradeoffs.
Use this table for each method:
| Step | Code Location | What Happens | Why It Happens | Failure/Edge Case |
|---|---|---|---|---|
| 1 | Service.method | Behavior. | Rationale. | Error/branch. |
16.4 Data Layer Deep Dive
Every table, collection, cache object, and queued payload must include:
- Ownership.
- Full field table.
- Field-level business meaning.
- Field-level nullability.
- Field-level validation source.
- Indexes and why they exist.
- Constraints and what bug they prevent.
- FK delete behavior.
- Soft-delete behavior.
- Versioning fields.
- Audit fields.
- Money units.
- Timezone and date interpretation.
- JSON schema examples.
- Migration history if relevant.
- Seed data dependency if relevant.
Add an index rationale table:
| Index/Constraint | Columns | Type | Query/Invariant Supported | Tradeoff |
|---|---|---|---|---|
index_name | column_a, column_b | btree/unique/gin/trgm | Query or invariant. | Write overhead/storage. |
16.5 Business Logic and Invariant Catalog
Every invariant enforced by code or schema must appear.
| Invariant | Enforced By | Why It Exists | Failure Error | Tests |
|---|---|---|---|---|
| Rule text | DTO/service/schema/job | Business reason. | Error code or DB error. | Spec path |
Include:
- State transition rules.
- Ownership rules.
- Visibility rules.
- Guest/user/admin rules.
- Catalog and pricing rules.
- Uniqueness rules.
- Idempotency rules.
- Cache invalidation rules.
- Async retry rules.
16.6 Tradeoffs, Alternatives, and ADR Notes
For every meaningful backend decision, include an ADR-style row.
| Decision | Context | Chosen Option | Alternatives | Why Chosen | Tradeoffs | Revisit Trigger |
|---|---|---|---|---|---|---|
| Decision title | Problem. | Current implementation. | Alternatives. | Rationale. | Costs/risks. | When to revisit. |
Cover:
- Module boundaries.
- DB vs cache ownership.
- SQL vs MongoDB.
- Sync vs async processing.
- Transaction boundaries.
- Failure handling.
- Cache TTL/invalidation.
- Queue retry/idempotency.
- Reuse vs local helper.
- Public ID vs internal ID.
16.7 Operational Runbook
| Operation | How to Inspect | Healthy State | Failure Signal | Recovery |
|---|---|---|---|---|
| Cache | Command/log/metric | Expected behavior. | Error/warn/latency. | Invalidate/restart/retry. |
| Queue | Bull Board/logs | Jobs completing. | Failed/delayed jobs. | Retry/DLQ/manual fix. |
| DB | Query/log | Constraints satisfied. | Deadlock/slow query. | Index/rollback/manual fix. |
16.8 Backend Risk Register
| Risk | Area | Impact | Current Mitigation | Remaining Gap |
|---|---|---|---|---|
| Race condition | Service/write path | Duplicate or stale data | Unique constraint/idempotency | Gap if any. |
17. Zero-Omission Backend Checklist
- Every file in the module directory is represented or explicitly marked non-runtime.
- Every controller, service, provider, processor, scheduler, helper, mapper, DTO, enum, and schema is documented.
- Every method with business behavior has a code-flow narrative.
- Every table/collection/cache object/job payload has field-level detail.
- Every index, constraint, relation, and delete behavior has rationale.
- Every lifecycle/status transition has a state diagram and transition table.
- Every read/write/action/job flow has sequence and activity diagrams.
- Every business invariant is cataloged.
- Every cache key, invalidation path, queue job, realtime event, and external call is documented.
- Every architectural tradeoff is documented with alternatives and revisit triggers.
- Every operational failure mode has a runbook entry.
18. Backend Completion Checklist
- Module boundaries are documented.
- Every controller, service, DTO, schema file, job, cache key, and event is covered.
- Every database table/collection has a field table and relationship diagram.
- Every runtime flow has a diagram and branch notes.
- API, feature/flows, and TDD docs are linked.
- No claim is made without a source file or documented source reference.
See Also
- API doc:
/docs/developer/MODULE_SLUG/api - Features and flows doc:
/docs/developer/MODULE_SLUG/feature - TDD:
/docs/developer/MODULE_SLUG/tdd