ajyadav013/claude-kit/backend-repo-architecture
Claude Code and agent skill by ajyadav013/claude-kit
- community
Checking that the SKILL.md file is still in the repository.
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.
Install
npx vskill@latest install ajyadav013/claude-kit/backend-repo-architectureSKILL.md
The same SKILL.md was published earlier as ajyadav013/claude-kit/backend-repo-architecture.
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.pyat repo root dispatches onMODEenvironment variable- Supported modes:
server,consumer,temporal_worker,worker,cron,webhook_server servermode runsuvicorn 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() -> FastAPIconstructs the app instance- Sets
debug=settings.DEBUG,lifespan=lifespan,default_response_class=ORJSONResponse - Includes
redirect_slashes=Falseto prevent ambiguous routing - Adds CORS middleware with
allow_origins,allow_credentials,allow_methods,allow_headers - Includes
api_routerviaapp.include_router(api_router) - May mount additional ASGI apps (e.g.,
/metricsfor Prometheus) - Optionally sets
root_pathfor multi-deployment routing
Router aggregation (app/router.py or src/main.py):
api_router = APIRouter()aggregates all domain routers- Health checks registered as
/_healthzand/_readyz - Domain routers included under version prefix (e.g.,
/v1) - Routers may be conditionally registered based on
DEPLOYMENT_NAMEorSERVER_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
ORJSONResponsewith consistent error format
Connection management (app/connection.py):
ConnectionManagersingleton (via__new__or Singleton metaclass) managesAsyncEngine, scoped session factory, and Redis clientasync_scoped_session(sessionmaker(engine, expire_on_commit=False, class_=AsyncSession), scopefunc=current_task)ConnectionHandlerper-request wrapper provides lazy.sessionand.redisproperties- Supports RLS via
set_tenant_context(tenant_id)and schema switching viaset_schema_context(schema_name) get_connection_handler()dependency yields a handler and callshandler.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):
BaseDaoprovidescreate,get_by_pk,update_by_pk,delete_by_pk,get_by_filter,get_paginated_response,bulk_insert,bulk_update- Soft-delete aware: checks
is_deletedanddeleted_atattributes - All queries go through
_execute_query(query)which rolls back on error - Pagination supports
page_size,page_number,sort_by,order_bywith 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
Settingsclass, module-levelsettings = Settings() - Pattern B:
loaded_config = Settings()singleton, plusconfig_parser.pyfor 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_TYPEenv var gates router inclusion (public/internal/platform/webhook) custom_openapi()rewrites paths withroot_pathlike/service/{SERVER_TYPE}/product/feature- Conditional
include_router()based onloaded_config.SERVER_TYPE
Skeleton / example
Flat domain example:
Versioned domain example:
Entrypoint MODE dispatch:
Application factory:
ConnectionHandler:
Lifespan:
Multi-deployment router gating:
Anti-patterns to avoid
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/backend-repo-architecture/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/ajyadav013/claude-kit/backend-repo-architecture)