CLAUDE.md TemplatesTemplate

FastAPI + CockroachDB + Clerk Auth + SQLModel Async Cluster Setup - CLAUDE.md Template

A copyable CLAUDE.md template page for FastAPI with CockroachDB, Clerk authentication, and SQLModel in an async cluster setup. Includes a ready-to-paste CLAUDE.md block.

CLAUDE.md TemplateFastAPICockroachDBClerkSQLModelAsyncClusterClaude CodePythonPostgreSQL

Target User

Backend engineers building scalable Python services

Use Cases

  • Scaffold a FastAPI service with CockroachDB
  • Integrate Clerk authentication
  • Leverage SQLModel with async sessions
  • Deploy to a multi-region CockroachDB cluster

Markdown Template

FastAPI + CockroachDB + Clerk Auth + SQLModel Async Cluster Setup - CLAUDE.md Template

# CLAUDE.md

Project role: You are a backend engineer and systems architect building a FastAPI app that uses CockroachDB as the primary data store, Clerk for authentication, and SQLModel for ORM in an async cluster setup.

Architecture rules:
- Build with FastAPI and async endpoints
- Use CockroachDB as a globally distributed cluster with TLS
- Authenticate via Clerk tokens for protected routes
- Use SQLModel with async sessions for all DB operations
- Favor repository/service pattern over monolithic handlers
- Ensure idempotent, deterministic migrations or schema setup
- Do not mix sync IO in request handlers

File structure rules:
- src/app/ as the root of the application
- src/app/models/ for SQLModel models
- src/app/api/v1/ for route definitions
- src/app/db/ for database utilities and sessions
- src/app/auth/ for Clerk integration and security guards
- src/app/config.py for environment configuration

Authentication rules:
- All protected endpoints require a valid Clerk session or Clerk-issued JWT
- Validate Clerk claims (subject, roles) on every protected route
- Do not process protected requests without Clerk authentication

Database rules:
- Connect to CockroachDB via a Postgres-compatible driver using SQLModel async APIs
- Use the DATABASE_URL environment variable; TLS required for all connections
- Use AsyncSession for all DB interactions
- Define indexes and constraints via SQLModel models; avoid raw SQL when ORM suffices
- Do not bypass ORM for reads/writes on documented endpoints

Validation rules:
- Use Pydantic/SQLModel validation for request bodies, query params, and path params
- Validate error payloads to a consistent shape
- Do not expose internal ORM details in responses

Security rules:
- Enforce TLS in all environments; reject plaintext HTTP in prod
- Do not log sensitive information (secrets, tokens, passwords)
- Use appropriate CORS settings; implement rate limiting on auth endpoints

Testing rules:
- Unit tests for models, utilities, and auth guards
- Integration tests for DB operations using a test CockroachDB or test container
- Mock Clerk responses in unit tests; end-to-end tests against a test cluster when feasible
- CI must cover linting, typing, and tests

Deployment rules:
- Dockerfile to containerize FastAPI app
- docker-compose.yml for local development with CockroachDB service
- Kubernetes manifests or Helm charts for production deployments
- Use environment variables for secrets; avoid hard-coded values

Things Claude must not do:
- Do not embed real secrets or credentials in the CLAUDE.md
- Do not bypass Clerk authentication checks
- Do not perform synchronous DB operations in async handlers
- Do not rely on a single-node CockroachDB in a multi-region deployment

Overview

CLAUDE.md template for a FastAPI + CockroachDB + Clerk Auth + SQLModel Async Cluster Setup. This page provides a copyable CLAUDE.md block and stack-specific guidance to generate end-to-end code usable in Claude Code. Direct answer: use this CLAUDE.md Template to scaffold an async FastAPI service backed by CockroachDB with Clerk authentication and SQLModel ORM.

When to Use This CLAUDE.md Template

  • You need an async FastAPI service connected to a multi-region CockroachDB cluster.
  • You require Clerk-based authentication integrated into FastAPI endpoints.
  • You want to use SQLModel as the ORM with async sessions for database access.
  • You plan to deploy to a cluster (Docker Compose for local, Kubernetes or cloud for prod).
  • You want a deterministic, copyable CLAUDE.md template that guides Claude Code instructions end-to-end.

Copyable CLAUDE.md Template

# CLAUDE.md

Project role: You are a backend engineer and systems architect building a FastAPI app that uses CockroachDB as the primary data store, Clerk for authentication, and SQLModel for ORM in an async cluster setup.

Architecture rules:
- Build with FastAPI and async endpoints
- Use CockroachDB as a globally distributed cluster with TLS
- Authenticate via Clerk tokens for protected routes
- Use SQLModel with async sessions for all DB operations
- Favor repository/service pattern over monolithic handlers
- Ensure idempotent, deterministic migrations or schema setup
- Do not mix sync IO in request handlers

File structure rules:
- src/app/ as the root of the application
- src/app/models/ for SQLModel models
- src/app/api/v1/ for route definitions
- src/app/db/ for database utilities and sessions
- src/app/auth/ for Clerk integration and security guards
- src/app/config.py for environment configuration

Authentication rules:
- All protected endpoints require a valid Clerk session or Clerk-issued JWT
- Validate Clerk claims (subject, roles) on every protected route
- Do not process protected requests without Clerk authentication

Database rules:
- Connect to CockroachDB via a Postgres-compatible driver using SQLModel async APIs
- Use the DATABASE_URL environment variable; TLS required for all connections
- Use AsyncSession for all DB interactions
- Define indexes and constraints via SQLModel models; avoid raw SQL when ORM suffices
- Do not bypass ORM for reads/writes on documented endpoints

Validation rules:
- Use Pydantic/SQLModel validation for request bodies, query params, and path params
- Validate error payloads to a consistent shape
- Do not expose internal ORM details in responses

Security rules:
- Enforce TLS in all environments; reject plaintext HTTP in prod
- Do not log sensitive information (secrets, tokens, passwords)
- Use appropriate CORS settings; implement rate limiting on auth endpoints

Testing rules:
- Unit tests for models, utilities, and auth guards
- Integration tests for DB operations using a test CockroachDB or test container
- Mock Clerk responses in unit tests; end-to-end tests against a test cluster when feasible
- CI must cover linting, typing, and tests

Deployment rules:
- Dockerfile to containerize FastAPI app
- docker-compose.yml for local development with CockroachDB service
- Kubernetes manifests or Helm charts for production deployments
- Use environment variables for secrets; avoid hard-coded values

Things Claude must not do:
- Do not embed real secrets or credentials in the CLAUDE.md
- Do not bypass Clerk authentication checks
- Do not perform synchronous DB operations in async handlers
- Do not rely on a single-node CockroachDB in a multi-region deployment

Recommended Project Structure

fastapi-cockroachdb-clerk-sqlmodel/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── config.py
│   ├── db/
│   │   ├── base.py
│   │   ├── session.py
│   │   └── migrations/
│   ├── models/
│   │   ├── user.py
│   │   └── item.py
│   ├── schemas/
│   │   └── user_schema.py
│   ├── auth/
│   │   └── clerk_auth.py
│   ├── api/
│   │   └── v1/
│   │       ├── endpoints.py
│   │       └── dependencies.py
│   └── clerk/
│       └── clerk_integration.py
├── tests/
├── docker/
│   ├── Dockerfile
│   └── docker-compose.yml
├── kubernetes/
│   └── deployment.yaml
├── pyproject.toml
├── requirements.txt

Core Engineering Principles

  • Explicit async programming: all DB and IO must be async.
  • Single source of truth: central config management with environment-based overrides.
  • Layered architecture: clear separation between API, business logic, and data access.
  • Security by default: least privilege, protected endpoints, and secret handling.
  • Observability: structured logging, tracing, and metrics for production.
  • Idempotent deployments: deterministic migrations and predictable rollouts.

Code Construction Rules

  • Use SQLModel models with async sessions for all interactions with CockroachDB.
  • Connection URLs come from DATABASE_URL; TLS must be enabled.
  • All authentication must be Clerk-based; validate tokens on protected routes.
  • Endpoints must be async; avoid blocking calls in request handlers.
  • Implement a repository/service layer to decouple business logic from routing.
  • Do not use raw SQL for standard operations; use ORM features and parameterized queries when needed.
  • Environment-driven configuration; never hard-code credentials.
  • Favor dependency injection for shared resources (DB sessions, Clerk client).

Security and Production Rules

  • Enforce TLS for CockroachDB and API endpoints in all environments.
  • Mask and avoid logging secrets, tokens, or personal data.
  • Validate input schemas strictly; return uniform error responses.
  • Implement proper CORS policies and rate limiting on authentication flows.
  • Regularly rotate credentials and use short-lived Clerk tokens where possible.

Testing Checklist

  • Unit tests for models and utilities with fixtures for Clerk mocks.
  • Integration tests verifying Async SQLModel usage against a test CockroachDB cluster.
  • End-to-end tests of auth flows using Clerk mocks.
  • Static type checking (mypy/pyright) and linting (ruff/black).
  • CI workflow runs tests on push/PR with dependency caching.

Common Mistakes to Avoid

  • Underestimating the complexity of multi-region CockroachDB configuration.
  • Forgetting to enforce TLS on DB connections and endpoints.
  • Using sync DB calls inside request handlers.
  • Hard-coding credentials or secret keys in source code.
  • Overly permissive Clerk token validation or missing role checks.

FAQ

Can I use this template with other ORMs besides SQLModel?

This CLAUDE.md Template is tailored for SQLModel with AsyncSession. For other ORMs, adapt the ORM usage while keeping async guidelines and Clerk integration intact.

How do I connect to a CockroachDB cluster in production?

Set DATABASE_URL to the CockroachDB connection string with TLS enabled. Use the PostgreSQL driver (postgresql+asyncpg) and ensure cluster TLS certs are trusted by the runtime.

How is Clerk integrated in FastAPI?

Use Clerk's Python SDK or REST calls to validate tokens on protected routes. Validate subject and role claims in dependencies and attach user context to request state.

What should I test in this setup?

Test model serialization, async DB interactions, Clerk-authenticated routes, and cluster resilience. Include tests for failure modes (expired tokens, DB timeouts, network partitions).

How do I deploy this in Kubernetes?

Provide Docker image, Kubernetes Deployment/StatefulSet for FastAPI app, and a CockroachDB StatefulSet or managed cluster. Use ConfigMaps/Secrets for config and TLS materials.