Skip to content
Agentmart
Submit a tool

backend-repo-architecture

Canonical backend repository structure for Python/FastAPI — multi-mode entrypoint, app factory, ConnectionManager, BaseDao, flat vs versioned layout.

Skill by ajyadav013

IndexedMIT★ 14
Write a review

Chalk Labs

Need help deploying backend-repo-architecture?

Chalk Labs sets up agents like this inside real teams: connected to your tools, tested on your data, with a human in the loop where it matters.

Book a call

Install

Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.

npx agentmarket install skill/ajyadav013-backend-repo-architecture

Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.

Get the weekly diff

The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.

We use your email only for this newsletter. Privacy

About

Canonical backend repository structure for Python/FastAPI — multi-mode entrypoint, app factory, ConnectionManager, BaseDao, flat vs versioned layout. Use when scaffolding or reorganizing a FastAPI service.

Use cases: backend, agent-building

No reviews yet. Installed it? Reviews come from verified installers only. How reviews work

Permissions

What this skill can do and what it asks for, from its SKILL.md and code. Checked Oct 26, 2026.

Tools
No tools found
Secrets
None asked for
Install scripts
None found

Network hosts it talks to 1

  • codeload.github.com · found in install command

Files it touches

  • ~/.claude/skills/backend-repo-architecture

What's inside

Skill name
backend-repo-architecture
Description
Canonical backend repository structure for Python/FastAPI — multi-mode entrypoint, app factory, ConnectionManager, BaseDao, flat vs versioned layout. Use when scaffolding or reorganizing a FastAPI service.
License
MIT
Instructions
296 lines in SKILL.md · view on GitHub

Files (6)

  • SKILL.md
  • deployment-patterns.md · references/
  • entrypoint-and-config.md · references/
  • repo-evidence.md · references/
  • structure-patterns.md · references/
  • troubleshooting.md · references/

SKILL.md (first lines)

# Backend Repository Architecture

A canonical backend archetype for Python/FastAPI services, derived from real-world production systems.

## When to use

- Scaffolding a new FastAPI backend service
- Reorganizing an existing backend to match team conventions
- Understanding the standard service layout and responsibilities
- Choosing between flat vs versioned domain layouts
- Setting up multi-mode deployment (server + workers + consumers)
- Implementing the standard config/connection/routing patterns

## Core conventions

All conventions below are derived from production Python/FastAPI services:
- **Reference service A** (cleanest reference, server-only, SQLAlchemy 2.0, versioned domains)
- **Reference service B** (largest ~48 domain modules, flat layout, MODE dispatcher)
- **Reference service C** (monorepo: apps/ + packages/, MODE dispatcher)
- **Reference service D** (multi-deployment: SERVER_TYPE router gating, MODE dispatcher)

**Entrypoint dispatcher** (used by services B, C, D):
- `entrypoint.py` at repo root dispatches on `MODE` environment variable
- Supported modes: `server`, `consumer`, `temporal_worker`, `worker`, `cron`, `webhook_server`
- `server` mode runs `uvicorn app.application:get_app --factory=True`
- Worker/consumer modes call `asyncio.run(service_main())` on the respective service module
- Each mode may initialize metrics/telemetry before dispatching
- **Note**: Service A is server-only (no entrypoint.py, Dockerfile runs gunicorn directly)

**Application factory** (app/application.py):
- `get_app() -> FastAPI` constructs the app instance
- Sets `debug=settings.DEBUG`, `lifespan=lifespan`, `default_response_class=ORJSONResponse`
- Includes `redirect_slashes=False` to prevent ambiguous routing
- Adds CORS middleware with `allow_origins`, `allow_credentials`, `allow_methods`, `allow_headers`
- Includes `api_router` via `app.include_router(api_router)`
- May mount additional ASGI apps (e.g., `/metrics` for Prometheus)
- Optionally sets `root_path` for multi-deployment routing

**Router aggregation** (app/router.py or src/main.py):
- `api_router = APIRouter()` aggregates all domain routers
- Health checks registered as `/_healthz` and `/_readyz`
- Domain routers included under version prefix (e.g., `/v1`)
- Routers may be conditionally registered based on `DEPLOYMENT_NAME` or `SERVER_TYPE` (multi-deployment variant)
- Uses `include_router(domain_router, prefix="/v1", tags=["Domain"])`

**Custom routing** (app/routing.py):
- `CustomRequestRoute(APIRoute)` provides centralized request/response logging, timing, exception handling
- Wraps all validation/HTTP/unhandled exceptions into a `ResponseData.error()` envelope
- Logs every request with method, path, status_code, duration
- Returns `ORJSONResponse` with consistent error format

**Connection management** (app/connection.py):
- `ConnectionManager` singleton (via `__new__` or Singleton metaclass) manages `AsyncEngine`, scoped session factory, and Redis client
- `async_scoped_session(sessionmaker(engine, expire_on_commit=False, class_=AsyncSession), scopefunc=current_task)`
- `ConnectionHandler` per-request wrapper provides lazy `.session` and `.redis` properties
- Supports RLS via `set_tenant_context(tenant_id)` and schema switching via `set_schema_context(schema_name)`
- `get_connection_handler()` dependency yields a handler and calls `handler.close()` on teardown

**Lifetime hooks** (app/lifetime.py):
- `@asynccontextmanager async def lifespan(app: FastAPI)` manages startup/shutdown
- Startup: `setup_logging()`, `ConnectionManager()`, Kafka producer, Temporal client, Redis
- Shutdown: close ConnectionManager, dispose engine, close Redis, shutdown telemetry

**Base DAO** (app/dao.py):
- `BaseDao` provides `create`, `get_by_pk`, `update_by_pk`, `delete_by_pk`, `get_by_filter`, `get_paginated_response`, `bulk_insert`, `bulk_update`
- Soft-delete aware: checks `is_deleted` and `deleted_at` attributes
- All queries go through `_execute_query(query)` which rolls back on error
- Pagination supports `page_size`, `page_number`, `sort_by`, `order_by` with column validation

**Database base** (app/database.py):
- SQLAlchemy 1.4 repos: `Base = declarative_base()`
- SQLAlchemy 2.0 repos: `class Base(DeclarativeBase): pass`
- All ORM models inherit from `Base`

**Config pattern** (config/settings.py or src/config/docker_config.py):
- `Settings(BaseSettings)` with pydantic-settings for typed environment variables
- Pattern A: single `Settings` class, module-level `settings = Settings()`
- Pattern B: `loaded_config = Settings()` singleton, plus `config_parser.py` for configargparse-based YAML/env merging
- All services consume `DATABASE_URL`, `REDIS_URL`, `DEBUG`, `CORS_ORIGINS`, `KAFKA_BOOTSTRAP_SERVERS`, `TEMPORAL_HOST`, etc.

**Domain layout: flat variant**:
- Top-level `src/<domain>/` for many domain modules
- Each module has `router.py`, `service.py`, `dao.py`, `models.py`, `schemas.py`, `helper.py`, `constant.py`
- Single-file per concern (no subdirectories within a domain)

**Domain layout: versioned variant**:
- `<pkg>/<domain>/v1/{router,service,dao,models,schemas,helper,workflows}.py`
- Allows side-by-side v1/v2 implementations

**Monorepo variant**:
- `apps/` (api, orchestrator, workers, forwarders)
- `packages/` (common, contracts, db, sdk)
- `services/` (infra packages like Kafka, Temporal)
- Each app has its own `application.py`, `router.py`, `lifetime.py`

**Multi-deployment variant**:
- Single codebase, `SERVER_TYPE` env var gates router inclusion (public/internal/platform/webhook)
- `custom_openapi()` rewrites paths with `root_path` like `/service/{SERVER_TYPE}/product/feature`
- Conditional `include_router()` based on `loaded_config.SERVER_TYPE`

## Skeleton / example

```
backend/
├── entrypoint.py              # MODE dispatcher (server/consumer/temporal_worker/cron) — OPTIONAL, omit for server-only
├── alembic/                   # DB migrations
├── alembic.ini
├── pyproject.toml
├── Dockerfile
├── app/                       # (or src/)
│   ├── application.py         # get_app() factory
│   ├── router.py              # api_router aggregation
│   ├── routing.py             # CustomRequestRoute (optional but recommended)
│   ├── connection.py          # ConnectionManager, ConnectionHandler, get_connection_handler
│   ├── dao.py                 # BaseDao
│   ├── database.py            # Base (declarative base)
│   ├── lifetime.py            # lifespan context manager
│   ├── main.py                # uvicorn runner (server mode)
│   ├── telemetry.py           # OpenTelemetry instrumentation (optional)

From ajyadav013/claude-kit, MIT.

More from ajyadav013/claude-kit

Signals

Stars
14
Forks
5
Open issues
9
Last commit (this folder)
Aug 22, 2026 (2 months ago)
Last release
Sep 7, 2026 (1 month ago)

From GitHub (fetched Oct 24, 2026).

Details

License
MIT
First seen
Oct 24, 2026
Last checked
Oct 24, 2026

More from ajyadav013

Done for you

Rather not set it up yourself?

Chalk Labs scopes, builds and runs agents for your team: the task audit, the eval harness, the integrations and the weekly ops report. Fixed scope, priced before we start.

See how we build AI agents →Read the case studies

Chalk Labs is a two-founder AI and growth studio. We build AI agents, CRMs and MVPs for Web3 and AI companies, and have shipped 50+ product and token launches.

launches shipped
50+
launches shipped
media placements
500+
media placements
founders on every account
2
founders on every account

Press we've placed: Forbes · CoinDesk · Decrypt · Cointelegraph · The Block

Rahil Jain, Co-founder, Chalk Labs. Ex-Goldman Sachs engineer. You talk to the person who builds it.

Get backend-repo-architecture running in your business

Tell us what you want to automate. A founder replies within one working day with a plan, not a pitch deck.

Goes to the Chalk Labs founders, not the newsletter. Privacy

Need help deploying backend-repo-architecture?

CallGet help
Cite this page

backend-repo-architecture skill. Agent Mart. https://agentmart.dev/skills/ajyadav013-backend-repo-architecture (last updated 2026-10-24)