backend-repo-architecture
Canonical backend repository structure for Python/FastAPI — multi-mode entrypoint, app factory, ConnectionManager, BaseDao, flat vs versioned layout.
Skill by ajyadav013
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.
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.
About
Use cases: backend, agent-building
Reviews
Write a reviewNo 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
- 0.602score
design-patterns-and-conventions
ajyadav013
Cross-cutting design patterns, naming, folder layout, and anti-patterns for production Python/FastAPI backends.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
async-python-patterns
ajyadav013
Async Python for high-performance services.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
data-engineering-bigquery-gcs
ajyadav013
BigQuery medallion architecture (bronze/silver/gold), parameterized queries, MERGE upserts, partitioning, CDC dedup, Temporal orchestration.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
cron-and-scheduled-jobs
ajyadav013
Scheduled jobs across two mechanisms — Kubernetes CronJobs (schedule in Helm values, MODE=cron) and Temporal Schedules.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
api-and-interface-design
ajyadav013
Stable API and interface design patterns.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
api-pagination-filtering-sorting
ajyadav013
HTTP query parameter conventions for pagination, filtering, sorting, and search with standardized response metadata.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
code-simplification
ajyadav013
Simplifies/refactors working code for clarity without changing behavior.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
auth-and-rbac
ajyadav013
FastAPI auth patterns — session/JWT chains, argon2id hashing, pyotp TOTP/Email OTP, role-based access control, x-user-data gateway forwarding.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
docker-shared
ajyadav013
Shared Docker building blocks — base images for private registries, .dockerignore conventions, compose fragment reuse with YAML anchors.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
dockerfile-backend
ajyadav013
Multi-stage Dockerfiles for Python/FastAPI backends — builder vs runtime, slim vs alpine, system deps, layer caching, non-root users.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
anthropic-vertex-integration
ajyadav013
Claude on Vertex AI via the AnthropicVertex SDK — lazy ADC client init, env-based project/region resolution, async helpers, backoff retry.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
distributed-systems-patterns
ajyadav013
Distributed data placement and replication — consistent hashing/vnodes, sharding, N/W/R quorums, KV-store and cache anatomy, gossip failure detection, B-tree…
SkillBFreshness: B★ 14Claude Code +9
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
- Repository
- github.com/ajyadav013/claude-kit
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from ajyadav013
- 0.602score
code-simplification
ajyadav013
Simplifies/refactors working code for clarity without changing behavior.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
cron-and-scheduled-jobs
ajyadav013
Scheduled jobs across two mechanisms — Kubernetes CronJobs (schedule in Helm values, MODE=cron) and Temporal Schedules.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
docker-shared
ajyadav013
Shared Docker building blocks — base images for private registries, .dockerignore conventions, compose fragment reuse with YAML anchors.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
dockerfile-backend
ajyadav013
Multi-stage Dockerfiles for Python/FastAPI backends — builder vs runtime, slim vs alpine, system deps, layer caching, non-root users.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
anthropic-vertex-integration
ajyadav013
Claude on Vertex AI via the AnthropicVertex SDK — lazy ADC client init, env-based project/region resolution, async helpers, backoff retry.
SkillBFreshness: B★ 14Claude Code +9 - 0.602score
api-and-interface-design
ajyadav013
Stable API and interface design patterns.
SkillBFreshness: B★ 14Claude Code +9
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.
Cite this page
backend-repo-architecture skill. Agent Mart. https://agentmart.dev/skills/ajyadav013-backend-repo-architecture (last updated 2026-10-24)