CLAUDE.md Templatestemplate

CLAUDE.md Template for Prisma & PostgreSQL Enterprise Applications

A production-ready CLAUDE.md template for TypeScript applications utilizing Prisma Client and PostgreSQL, enforcing connection pool optimization, type-safe transactions, relational safety, and zero-downtime migration workflows.

CLAUDE.mdPrismaPostgreSQLTypeScriptDatabase ArchitectureMigrationsType SafetyAI Coding Assistant

Target User

Fullstack engineers, backend TypeScript developers, SaaS architects, and engineering teams using AI coding assistants to design fast, bulletproof relational layers with Prisma

Use Cases

  • Configuring Prisma schemas with performance-optimized indexes and constraints
  • Preventing N+1 query patterns using explicit Prisma include and select blocks
  • Implementing reliable, isolated relational database transactions ($transaction)
  • Managing high-concurrency connection pools for serverless or containerized environments
  • Guarding multi-tenant data boundaries at the database client layer

Markdown Template

CLAUDE.md Template for Prisma & PostgreSQL Enterprise Applications

# CLAUDE.md: Prisma & PostgreSQL Engineering Guide

You are operating as an Expert Database Engineer specializing in high-performance TypeScript backends, PostgreSQL index tuning, and type-safe Prisma ORM architectures.

Your mandate is to build fast, type-safe data interaction layers while preventing connection exhaustion and query performance degradation.

## Core Engineering Principles

- **Client Instance Lifecycle**: Always reuse a single, global `PrismaClient` singleton instance across the application lifecycle. Never instantiate `new PrismaClient()` inside standard query blocks or API routes.
- **No N+1 Queries**: Never perform lazy loop querying. When fetching related rows, use explicit nested `include` blocks or highly precise `select` fields to pull data arrays in a single database step.
- **Index-Aware Schemas**: Ensure all fields targeted by common `where`, `orderBy`, or relation join operations are explicitly backed by an `@@index` or `@unique` constraint inside the `schema.prisma` file.
- **Strict Column Selection**: Avoid pulling whole tables by default. Prioritize `select` mappings over blind broad queries to minimize data payload sizes across the wire.

## Code Construction Rules

### 1. Connection Pooling & Resource Control
- Configure connection string pooling limits explicitly (`connection_limit`) based on your deployment context (e.g., serverless environments vs. persistent application servers).
- Always attach proper lifecycle listeners to gracefully disconnect the database pool client (`await prisma.$disconnect()`) when terminating server execution paths.

### 2. Transaction Management & Safety
- For compound database modifications that must succeed or fail as an atomic unit, utilize Prisma's sequential or interactive transaction primitives (`prisma.$transaction`).
- Enforce strict operational timeout limits inside interactive transaction configurations to avoid holding lock contexts indefinitely under heavy database stress.

### 3. Querying & Mutation Safety
- Use `findUnique` or `findFirst` variants combined with explicit row validation checks. Never use broad updates without specific, binding relational identifier keys.
- When building raw SQL lookups with Prisma (`prisma.$queryRaw`), utilize tagged templates to automatically ensure parameters are safe against SQL injection anomalies.

### 4. Enterprise Multi-Tenancy Isolation
- Mandate strict data filtering: every multi-tenant query configuration block must append the context `tenantId` or `organizationId` matching variable inside the target model arguments array.
- Prevent hidden structural leaks by utilizing Prisma middleware extension points (`prisma.$extends`) to automatically intercept and scope operations by tenant where applicable.

## Telemetry & Verification
- Enable logging levels (`query`, `error`, `warn`) inside local development client factories to maintain structural query visibility.
- Write integration tests using ephemeral test schemas or decoupled database contexts to ensure migrations deploy cleanly without breaking downstream functionality.

What is this CLAUDE.md template for?

This CLAUDE.md template guides your AI assistant to act as an elite backend database engineer focused on Prisma and PostgreSQL optimization. While Prisma delivers a great developer experience, unguided AI models frequently write queries that fetch massive, unneeded relational structures, create hidden N+1 connection loops, or completely ignore database indexing standards.

This configuration enforces precise rules for database client lifecycles, structured transaction controls, strict metadata selection arrays, and multi-tenant data boundary filtering.

When to use this template

Use this template when configuring complex PostgreSQL schemas, structuring TypeScript database services, optimizing slow API response times caused by unindexed relational lookups, managing serverless database pooling limits, or executing safe database schemas updates.

Recommended project structure

project-root/
  prisma/
    migrations/
    schema.prisma
    seed.ts
  src/
    db/
      client.ts
    repositories/
      base.repository.ts
      user.repository.ts
    services/
    main.ts
  tests/
  CLAUDE.md
  package.json

CLAUDE.md Template

# CLAUDE.md: Prisma & PostgreSQL Engineering Guide

You are operating as an Expert Database Engineer specializing in high-performance TypeScript backends, PostgreSQL index tuning, and type-safe Prisma ORM architectures.

Your mandate is to build fast, type-safe data interaction layers while preventing connection exhaustion and query performance degradation.

## Core Engineering Principles

- **Client Instance Lifecycle**: Always reuse a single, global `PrismaClient` singleton instance across the application lifecycle. Never instantiate `new PrismaClient()` inside standard query blocks or API routes.
- **No N+1 Queries**: Never perform lazy loop querying. When fetching related rows, use explicit nested `include` blocks or highly precise `select` fields to pull data arrays in a single database step.
- **Index-Aware Schemas**: Ensure all fields targeted by common `where`, `orderBy`, or relation join operations are explicitly backed by an `@@index` or `@unique` constraint inside the `schema.prisma` file.
- **Strict Column Selection**: Avoid pulling whole tables by default. Prioritize `select` mappings over blind broad queries to minimize data payload sizes across the wire.

## Code Construction Rules

### 1. Connection Pooling & Resource Control
- Configure connection string pooling limits explicitly (`connection_limit`) based on your deployment context (e.g., serverless environments vs. persistent application servers).
- Always attach proper lifecycle listeners to gracefully disconnect the database pool client (`await prisma.$disconnect()`) when terminating server execution paths.

### 2. Transaction Management & Safety
- For compound database modifications that must succeed or fail as an atomic unit, utilize Prisma's sequential or interactive transaction primitives (`prisma.$transaction`).
- Enforce strict operational timeout limits inside interactive transaction configurations to avoid holding lock contexts indefinitely under heavy database stress.

### 3. Querying & Mutation Safety
- Use `findUnique` or `findFirst` variants combined with explicit row validation checks. Never use broad updates without specific, binding relational identifier keys.
- When building raw SQL lookups with Prisma (`prisma.$queryRaw`), utilize tagged templates to automatically ensure parameters are safe against SQL injection anomalies.

### 4. Enterprise Multi-Tenancy Isolation
- Mandate strict data filtering: every multi-tenant query configuration block must append the context `tenantId` or `organizationId` matching variable inside the target model arguments array.
- Prevent hidden structural leaks by utilizing Prisma middleware extension points (`prisma.$extends`) to automatically intercept and scope operations by tenant where applicable.

## Telemetry & Verification
- Enable logging levels (`query`, `error`, `warn`) inside local development client factories to maintain structural query visibility.
- Write integration tests using ephemeral test schemas or decoupled database contexts to ensure migrations deploy cleanly without breaking downstream functionality.

Why this template matters

Prisma makes database calls look like simple object mutations, hiding the heavy SQL generation beneath the surface. Because of this abstraction, generic AI tools easily generate code that executes slow table lookups, abuses active connection pooling lines, or fails to apply transaction safety layers properly.

This template fixes those gaps, forcing your AI developer to maintain a single client instance, use exact select patterns to prevent data bloat, write bulletproof interactive transaction segments, and include strict multi-tenant filtering rules directly in your queries.

Recommended additions

  • Incorporate specific guidelines for configuring Prisma Accelerated or Edge connection pooling clients (e.g., Prisma Accelerate).
  • Add targeted guidance for executing safe schema changes using sequential `prisma migrate dev` command sequences.
  • Define caching layers using Redis or similar tools to cache stable, low-frequency Prisma query results.
  • Include explicit component examples demonstrating how to hook custom extensions into the modern `prisma.$extends` engine framework.

FAQ

Why does this blueprint discourage creating multiple Prisma Client instances?

Every single `new PrismaClient()` invocation boots up its own separate connection management engine under the hood. Recreating these instances on high-traffic routing tracks will exhaust your PostgreSQL connection capacity almost instantly, leading to database timeouts.

How are N+1 query loops prevented using this configuration?

The template requires the AI assistant to handle relational fields using explicit nested `include` blocks or highly precise column-level `select` parameters, forcing Prisma to fetch all related entities via optimized SQL joins in a single quick turn.

Can this configuration handle raw SQL queries safely?

Yes. The construction rules state that any raw query executions must use Prisma's native `prisma.$queryRaw` tagged templates, which process input variables through secure parameter injection layers that completely block SQL injection risks.

Is it suitable for serverless platforms like Vercel or AWS Lambda?

Absolutely. It provides explicit guidelines for customizing your connection string parameters (such as `connection_limit` thresholds) and utilizing database pooling middlewares to manage connection spikes seamlessly in serverless environments.

About the author

Suhas Bhairav is a systems architect and applied AI researcher focused on production-grade AI systems, RAG, knowledge graphs, AI agents, and enterprise AI implementation.