Happy House - Ecommerce Docs
Developer Resourcesdocumentation formats

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

SourceRequired Use
Existing Fumadocs module docsUse 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.mdUse for API/DTO cross-reference structure.
Backend module filesRequired for module composition, providers, controllers, services, guards, and exports.
Schema filesRequired for tables, indexes, constraints, enums, relations, generated IDs, and migrations.
Infrastructure packagesRequired for Redis, BullMQ, realtime, MongoDB, storage, jobs, and shared utilities.
Tests and seed filesRequired 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

AreaFiles InspectedVerified Details
Module wiringapps/api/src/modules/MODULE_PATH/*.module.tsImports, providers, exports, route composition.
Controllers...controller.tsRoute ownership and thin-controller boundaries.
Services...service.tsBusiness logic, validation, writes, mappings, side effects.
DTOsdto/*.tsAPI contracts and validation.
Schemapackages/db/src/schema/...Tables, enums, relations, indexes.
Jobspackages/jobs/src/...Queue contracts and payloads.
CacheCacheKeyUtil, Redis servicesKey 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

ConcernSource of TruthNotes
Runtime stateDB/cache/session tableExplain authority.
IdentityAuth/guest identity moduleExplain guest/user/admin.
Score/timer/resultBackend serviceNever trust client-computed values.

3. Module Composition

Document aggregate and leaf modules.

ModuleTypePathControllersProvidersExportsResponsibility
MODULEModuleAggregateapps/api/src/modules/...None or listProvidersExportsComposes leaf modules.
SUBMODULEModuleLeafapps/api/src/modules/...ControllersServicesServicesOwns 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:

FilePurposeKey ExportsNotes
path/to/file.tsPurpose.ClassNameImportant behavior.

5. Data Model

5.1 Schema Source

packages/db/src/schema/MODULE/
  index.ts
  enums.ts
  table-name.ts

5.2 Tables and Collections

Repeat for every SQL table, Mongo collection, Redis state object, or persisted job payload.

TABLE_OR_COLLECTION_NAME

Column/FieldTypeNullableDefaultIndex/ConstraintRelationNotes
idserial or uuidNogeneratedPKN/AExplain 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

MethodCalled ByReadsWritesSide EffectsErrors
methodName()Controller/job/serviceTables/cacheTables/cacheJobs/events/cache invalidationError 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

StepCode PathBehaviorFailure Case
1Controller.methodReceives request.DTO validation error.
2Service.methodApplies 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 PatternBuilderValueTTLInvalidationCaller
module:key:segmentsCacheKeyUtil.build(...)ShapeSecondsExact invalidation sourceService

Explain:

  • Deterministic segment order.
  • Cache hit behavior.
  • Cache miss behavior.
  • Serialization shape.
  • Invalidation on mutations.
  • Failure handling.

9. BullMQ, Schedulers, and Async Work

QueueJobProducerProcessorPayloadRetry/BackoffIdempotency
QueueName.MODULEmodule.jobServiceProcessorPayload typeAttemptsJob ID rule

Add a diagram if jobs exist:

10. Realtime and Events

EventProducerRoom/TargetPayloadConsumerReliability Notes
event.nameServiceroom:idShapeClient/serviceDelivery 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 CodeHTTP StatusThrown ByConditionClient Action
MODULE_ERROR400Service.methodExact condition.Fix request/retry/login.

14. Observability

SignalLocationPurpose
LogLogger in service/processorFailure and state-change visibility.
MetricName if presentOperational monitoring.
AuditTable/event if presentAdmin/accountability tracking.

15. Testing and Validation

Test TypeFilesCoverage
Unit*.spec.tsService methods and edge cases.
Integration*.int-spec.tsDB/cache/jobs.
E2E*.e2e-spec.tsRoute contracts.
ManualCommandsVerified 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.

UnitTypeOwnsDepends OnCalled ByCallsState TouchedFailure Modes
ClassNameController/service/processorResponsibilityDependenciesRoutes/jobs/servicesDownstream callsDB/cache/job/eventErrors/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.

DiagramRequired WhenPurpose
Component diagramAlwaysShows modules, submodules, services, and infrastructure.
Class diagramAlways for non-trivial modulesShows controllers, services, DTOs, processors, and relationships.
ER diagramAny SQL persistenceShows table relationships, PKs, FKs, and join tables.
Collection/document diagramAny MongoDB persistenceShows document shape and indexes.
Sequence diagramEvery major read/write/action/job flowShows call order.
Activity diagramEvery complex service methodShows branches, validation, and side effects.
State diagramAny lifecycle/status/sessionShows allowed transitions.
Deployment/runtime diagramAny Redis/BullMQ/realtime/external dependencyShows runtime topology.
Data lineage diagramAny multi-step transformationShows 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:

  1. Entry point and caller.
  2. DTO/command shape.
  3. Auth/identity assumptions.
  4. Input normalization.
  5. Validation order.
  6. Reads performed.
  7. Business decisions.
  8. Writes performed.
  9. Transactions or lack of transaction.
  10. Cache behavior.
  11. Jobs/events/notifications.
  12. Response mapping.
  13. Error handling.
  14. Logs/metrics/audit events.
  15. Known tradeoffs.

Use this table for each method:

StepCode LocationWhat HappensWhy It HappensFailure/Edge Case
1Service.methodBehavior.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/ConstraintColumnsTypeQuery/Invariant SupportedTradeoff
index_namecolumn_a, column_bbtree/unique/gin/trgmQuery or invariant.Write overhead/storage.

16.5 Business Logic and Invariant Catalog

Every invariant enforced by code or schema must appear.

InvariantEnforced ByWhy It ExistsFailure ErrorTests
Rule textDTO/service/schema/jobBusiness 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.

DecisionContextChosen OptionAlternativesWhy ChosenTradeoffsRevisit Trigger
Decision titleProblem.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

OperationHow to InspectHealthy StateFailure SignalRecovery
CacheCommand/log/metricExpected behavior.Error/warn/latency.Invalidate/restart/retry.
QueueBull Board/logsJobs completing.Failed/delayed jobs.Retry/DLQ/manual fix.
DBQuery/logConstraints satisfied.Deadlock/slow query.Index/rollback/manual fix.

16.8 Backend Risk Register

RiskAreaImpactCurrent MitigationRemaining Gap
Race conditionService/write pathDuplicate or stale dataUnique constraint/idempotencyGap 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