Microservices
Directory structure
Section titled “Directory structure”src/ application/ # use cases, FastAPI endpoints (or Reflex pages for UI) domain/ # core business models and rules adapters/ # implementations of ports: DB clients, messaging integrations ports/ # interfaces for external systems: repositories, messaging main.py # entry point __init__.py # in src/ and every subdirectorytests/ # mirrors src/The dependency rule
Section titled “The dependency rule”domaindepends on nothing outside itself.portsdefines interfaces for external systems (repositories, messaging).adaptersimplements ports (database clients, messaging integrations).applicationorchestrates use cases against ports and domain.main.pywires adapters to ports and starts the app.
Consequences:
- A service is testable without spinning up a cluster: mock the ports.
- Swapping a database is a change in one adapter, not a rewrite.
- FastAPI, the message broker and the database are details at the edge, not the center.
Component view (representative service)
Section titled “Component view (representative service)”C4Componenttitle Component diagram for a microserviceContainer_Boundary(container_boundary, "microservice") { Component(application, "Application Layer", "FastAPI", "Use cases, API endpoints") Component(domain, "Domain Layer", "Python", "Core business models and rules") Component(adapters, "Adapters Layer", "Python", "Implementations of ports") Component(ports, "Ports Layer", "Python", "Interfaces for external systems") ComponentQueue(pubsub, "Message Broker", "Messaging", "Handles asynchronous communication") ComponentDb(statestore, "State Store", "Storage", "Manages state")}Rel(application, domain, "Uses")Rel(application, ports, "Uses")Rel(adapters, ports, "Implements")Rel(domain, adapters, "Uses")Rel(adapters, pubsub, "Publishes/Consumes")Rel(adapters, statestore, "Reads/Writes")Working rules
Section titled “Working rules”- Define the port first. Before writing a database client, write the interface it must satisfy.
- Keep the domain pure. No framework imports, no I/O, no broker calls in
domain/. - Adapters are replaceable. Each adapter implements one or more ports and nothing else.
- Application layer owns use cases. HTTP handlers stay thin; business orchestration lives in use cases.
- Tests mirror src/. Unit tests for domain and application; integration tests for adapters.
Local development
Section titled “Local development”Each microservice is self-contained: run it with docker-compose.yml and its component files from its own directory. No cluster required. That is only possible because the domain and application layers do not depend on Kubernetes — they depend on ports.
Further readings
Section titled “Further readings”- Dapr service mesh for state, pub/sub and resiliency.
- Kubernetes and Helm for the runtime layer.
- Docker foundations for container baselines.
