STACK IT FAST
ALL RULES & SKILLS

NestJS + PostgreSQL + Redis + BullMQ

Raw .MD nestjs-postgres-redis
CURATED RULE AGENTS.MD + CLAUDE.MD + .MDC + SKILL.MD

Enterprise backend architecture guidelines for NestJS modular design, PostgreSQL connection pooling, Redis BullMQ background jobs, and DTO validation.

AGENTS.md
Paste in your project root
SKILL.md
Installs to .claude/skills/nestjs-postgres-redis
INTERACTIVE RULE & SKILL VIEWER (AGENTS.MD, CLAUDE.MD, .MDC & SKILL.MD)
Optimized for:CursorClaude CodeWindsurfAGY
AGENTS.md·57 lines · 3.3 KB
1# Project Architecture & Guidelines (NestJS + PostgreSQL + Redis + BullMQ)
2
3## 1. System Architecture
4- **Framework**: NestJS (Modular architecture with Dependency Injection).
5- **Database**: PostgreSQL with TypeORM or Prisma ORM.
6- **Queue System**: BullMQ backed by Redis for asynchronous jobs and delayed tasks.
7- **Validation & Transformation**: `class-validator` and `class-transformer` via global `ValidationPipe`.
8
9## 2. PostgreSQL Connection Management
10- When scaling multiple NestJS container replicas, route connections through PgBouncer or configure explicit pool limits:
11 ```typescript
12 TypeOrmModule.forRootAsync({
13 imports: [ConfigModule],
14 inject: [ConfigService],
15 useFactory: (config: ConfigService) => ({
16 type: 'postgres',
17 url: config.get<string>('DATABASE_URL'),
18 autoLoadEntities: true,
19 synchronize: false, // NEVER true in production
20 extra: {
21 max: 20, // Max pool size per instance
22 idleTimeoutMillis: 30000,
23 connectionTimeoutMillis: 2000,
24 },
25 }),
26 })
27 ```
28
29## 3. Redis & BullMQ Queue Rules (Critical)
30- **Redis Eviction Policy**: Set Redis `maxmemory-policy` to `noeviction`. Evicting keys arbitrarily corrupts BullMQ queue states.
31- **Worker Process Isolation**: For heavy compute or long-running tasks, instantiate workers in dedicated background worker processes rather than the main API server process.
32- **Graceful Shutdown**: Always configure `enableShutdownHooks()` on the NestJS app instance to allow active BullMQ workers to finish jobs before container termination.
33
34## 4. Layer Organization & Dependency Injection
35- `src/modules/<resource>/`:
36 - `<resource>.controller.ts`: Pure HTTP routing, status codes, and Swagger decorators.
37 - `<resource>.service.ts`: Business logic and database operations.
38 - `<resource>.processor.ts`: BullMQ `@Processor` handler for background jobs.
39 - `dto/`: Strongly typed request/response DTOs with `@IsString()`, `@IsOptional()`, etc.
40 - `entities/`: Database schema entities.
41
42## 5. Common Pitfalls to Avoid
43- ❌ Enabling `synchronize: true` in production database config (causes data loss).
44- ❌ Non-idempotent job handlers: Always check if a background job was already completed before executing side effects.
45- ❌ Unhandled Worker Errors: Ensure workers implement event listeners (`@OnWorkerEvent('failed')`) to prevent silent crashes.
46
47## 6. Testing Conventions
48- Use Jest (NestJS default) with `@nestjs/testing`'s `Test.createTestingModule` to build isolated module contexts per test suite.
49- Mock BullMQ queues in unit tests (`getQueueToken()`); reserve real Redis-backed queue tests for a dedicated integration suite.
50- Write e2e tests with `supertest` against a running Nest app instance for every controller endpoint, not just services.
51- Assert processor idempotency explicitly: invoke the same job payload twice and assert no duplicate side effects.
52
53## 7. Git Workflow & PR Conventions
54- Conventional Commits (`feat:`, `fix:`, `refactor:`) scoped to the module, e.g. `fix(billing): prevent duplicate invoice job processing`.
55- TypeORM/Prisma migrations ship in the same PR as the entity change that generated them.
56- Require `bun run test`, `bun run test:e2e`, and `tsc --noEmit` green before merge.
57- Squash-merge feature branches; never merge with `synchronize: true` left enabled in any committed config.
ARCHITECTURE NOTES & IMPLEMENTATION GUIDE
Export as Markdown

Architecture Overview

Production conventions for scalable, enterprise-grade backend microservices and APIs with NestJS, PostgreSQL, Redis, and BullMQ.

Verified Real-World Adoption

This architecture is deployed in high-concurrency production platforms including Twenty CRM, ToolJet, Novu, AFFiNE, and Logto.

Key Architectural Nuances

  • Redis Memory Policy Safety: Requires noeviction policy to protect BullMQ queue integrity.
  • Dedicated Worker Topologies: Decouples HTTP request-response latency from asynchronous queue processing.
FREQUENTLY ASKED QUESTIONS

Does this AGENTS.md work with Cursor, Claude Code, and Windsurf?

Yes — AGENTS.md is the open, cross-tool standard read by Cursor, Claude Code, Windsurf, and 30+ other agents. A dedicated .mdc file is also included for Cursor's native .cursor/rules format.

Why must Redis use the noeviction policy for BullMQ?

BullMQ stores job state, delayed-job timers, and queue metadata as Redis keys, and treats that data as durable. If Redis is allowed to evict keys under memory pressure using an LRU or LFU policy, it can silently delete in-flight or delayed jobs along with your cache entries, causing jobs to vanish with no error.

Why run BullMQ workers in a separate process from the API server?

A long-running or CPU-heavy job executing inside the same Node.js process as your HTTP API blocks the single-threaded event loop, causing unrelated API requests to stall. Running workers as dedicated processes isolates job execution from request latency and lets you scale API replicas and worker replicas independently.

MORE AI AGENT CODING RULES & SKILLS
View All Rules & Skills