Skip to content

ever-co/ever-works / .agents/skills/nestjs-best-practices

nestjs-best-practices

Verified

NestJS best practices and architecture patterns for building production-ready applications. This skill should be used when writing, reviewing, or refactoring NestJS code to ensure proper patterns for modules, dependency injection, security, and performance.

FileKindSize
AGENTS.mdmarkdown154.2 KB
README.mdmarkdown4.7 KB
SKILL.mdskill md4.8 KB
rules/_sections.mdmarkdown2.1 KB
rules/_template.mdmarkdown633 B
rules/api-use-dto-serialization.mdmarkdown4.2 KB
rules/api-use-interceptors.mdmarkdown5.4 KB
rules/api-use-pipes.mdmarkdown5.3 KB
rules/api-versioning.mdmarkdown4.7 KB
rules/arch-avoid-circular-deps.mdmarkdown1.9 KB
rules/arch-feature-modules.mdmarkdown2.3 KB
rules/arch-module-sharing.mdmarkdown3.7 KB
rules/arch-single-responsibility.mdmarkdown2.8 KB
rules/arch-use-events.mdmarkdown2.9 KB
rules/arch-use-repository-pattern.mdmarkdown2.7 KB
rules/db-avoid-n-plus-one.mdmarkdown3.8 KB
rules/db-use-migrations.mdmarkdown3.7 KB
rules/db-use-transactions.mdmarkdown3.6 KB
rules/devops-graceful-shutdown.mdmarkdown5.5 KB
rules/devops-use-config-module.mdmarkdown4.2 KB
rules/devops-use-logging.mdmarkdown5.1 KB
rules/di-avoid-service-locator.mdmarkdown2.8 KB
rules/di-interface-segregation.mdmarkdown5.0 KB
rules/di-liskov-substitution.mdmarkdown6.8 KB
rules/di-prefer-constructor-injection.mdmarkdown2.2 KB
rules/di-scope-awareness.mdmarkdown2.5 KB
rules/di-use-interfaces-tokens.mdmarkdown2.5 KB
rules/error-handle-async-errors.mdmarkdown3.4 KB
rules/error-throw-http-exceptions.mdmarkdown3.0 KB
rules/error-use-exception-filters.mdmarkdown3.4 KB
rules/micro-use-health-checks.mdmarkdown6.1 KB
rules/micro-use-patterns.mdmarkdown5.0 KB
rules/micro-use-queues.mdmarkdown5.7 KB
rules/perf-async-hooks.mdmarkdown2.8 KB
rules/perf-lazy-loading.mdmarkdown3.6 KB
rules/perf-optimize-database.mdmarkdown3.0 KB
rules/perf-use-caching.mdmarkdown3.3 KB
rules/security-auth-jwt.mdmarkdown3.8 KB
rules/security-rate-limiting.mdmarkdown3.1 KB
rules/security-sanitize-output.mdmarkdown3.7 KB
rules/security-use-guards.mdmarkdown3.4 KB
rules/security-validate-all-input.mdmarkdown3.2 KB
rules/test-e2e-supertest.mdmarkdown4.4 KB
rules/test-mock-external-services.mdmarkdown4.2 KB
rules/test-use-testing-module.mdmarkdown4.1 KB
scripts/build-agents.tsscript8.1 KB
scripts/build.shscript369 B
scripts/package-lock.jsonmanifest7.7 KB
scripts/package.jsonmanifest410 B

rules/micro-use-queues.md

View on GitHub
---
title: Use Message Queues for Background Jobs
impact: MEDIUM-HIGH
impactDescription: Queues enable reliable background processing
tags: microservices, queues, bullmq, background-jobs
---

## Use Message Queues for Background Jobs

Use `@nestjs/bullmq` for background job processing. Queues decouple long-running tasks from HTTP requests, enable retry logic, and distribute workload across workers. Use them for emails, file processing, notifications, and any task that shouldn't block user requests.

**Incorrect (long-running tasks in HTTP handlers):**

```typescript
// Long-running tasks in HTTP handlers
@Controller('reports')
export class ReportsController {
	@Post()
	async generate(@Body() dto: GenerateReportDto): Promise<Report> {
		// This blocks the request for potentially minutes
		const data = await this.fetchLargeDataset(dto);
		const report = await this.processData(data); // Slow!
		await this.sendEmail(dto.email, report); // Can fail!
		return report; // Client times out
	}
}

// Fire-and-forget without retry
@Injectable()
export class EmailService {
	async sendWelcome(email: string): Promise<void> {
		// If this fails, email is never sent
		await this.mailer.send({ to: email, template: 'welcome' });
		// No retry, no tracking, no visibility
	}
}

// Use setInterval for scheduled tasks
setInterval(async () => {
	await cleanupOldRecords();
}, 60000); // No error handling, memory leaks
```

**Correct (use BullMQ for background processing):**

```typescript
// Configure BullMQ
import { BullModule } from '@nestjs/bullmq';

@Module({
	imports: [
		BullModule.forRoot({
			connection: {
				host: 'localhost',
				port: 6379
			},
			defaultJobOptions: {
				removeOnComplete: 1000,
				removeOnFail: 5000,
				attempts: 3,
				backoff: {
					type: 'exponential',
					delay: 1000
				}
			}
		}),
		BullModule.registerQueue({ name: 'email' }, { name: 'reports' }, { name: 'notifications' })
	]
})
export class QueueModule {}

// Producer: Add jobs to queue
@Injectable()
export class ReportsService {
	constructor(@InjectQueue('reports') private reportsQueue: Queue) {}

	async requestReport(dto: GenerateReportDto): Promise<{ jobId: string }> {
		// Return immediately, process in background
		const job = await this.reportsQueue.add('generate', dto, {
			priority: dto.urgent ? 1 : 10,
			delay: dto.scheduledFor ? Date.parse(dto.scheduledFor) - Date.now() : 0
		});

		return { jobId: job.id };
	}

	async getJobStatus(jobId: string): Promise<JobStatus> {
		const job = await this.reportsQueue.getJob(jobId);
		return {
			status: await job.getState(),
			progress: job.progress,
			result: job.returnvalue
		};
	}
}

// Consumer: Process jobs
@Processor('reports')
export class ReportsProcessor {
	private readonly logger = new Logger(ReportsProcessor.name);

	@Process('generate')
	async generateReport(job: Job<GenerateReportDto>): Promise<Report> {
		this.logger.log(`Processing report job ${job.id}`);

		// Update progress
		await job.updateProgress(10);

		const data = await this.fetchData(job.data);
		await job.updateProgress(50);

		const report = await this.processData(data);
		await job.updateProgress(90);

		await this.saveReport(report);
		await job.updateProgress(100);

		return report;
	}

	@OnQueueActive()
	onActive(job: Job) {
		this.logger.log(`Processing job ${job.id}`);
	}

	@OnQueueCompleted()
	onCompleted(job: Job, result: any) {
		this.logger.log(`Job ${job.id} completed`);
	}

	@OnQueueFailed()
	onFailed(job: Job, error: Error) {
		this.logger.error(`Job ${job.id} failed: ${error.message}`);
	}
}

// Email queue with retry
@Processor('email')
export class EmailProcessor {
	@Process('send')
	async sendEmail(job: Job<SendEmailDto>): Promise<void> {
		const { to, template, data } = job.data;

		try {
			await this.mailer.send({
				to,
				template,
				context: data
			});
		} catch (error) {
			// BullMQ will retry based on job options
			throw error;
		}
	}
}

// Usage
@Injectable()
export class NotificationService {
	constructor(@InjectQueue('email') private emailQueue: Queue) {}

	async sendWelcome(user: User): Promise<void> {
		await this.emailQueue.add(
			'send',
			{
				to: user.email,
				template: 'welcome',
				data: { name: user.name }
			},
			{
				attempts: 5,
				backoff: { type: 'exponential', delay: 5000 }
			}
		);
	}
}

// Scheduled jobs
@Injectable()
export class ScheduledJobsService implements OnModuleInit {
	constructor(@InjectQueue('maintenance') private queue: Queue) {}

	async onModuleInit(): Promise<void> {
		// Clean up old reports daily at midnight
		await this.queue.add(
			'cleanup',
			{},
			{
				repeat: { cron: '0 0 * * *' },
				jobId: 'daily-cleanup' // Prevent duplicates
			}
		);

		// Send digest every hour
		await this.queue.add(
			'digest',
			{},
			{
				repeat: { every: 60 * 60 * 1000 },
				jobId: 'hourly-digest'
			}
		);
	}
}

@Processor('maintenance')
export class MaintenanceProcessor {
	@Process('cleanup')
	async cleanup(): Promise<void> {
		await this.cleanupOldReports();
		await this.cleanupExpiredSessions();
	}

	@Process('digest')
	async sendDigest(): Promise<void> {
		const users = await this.getUsersForDigest();
		for (const user of users) {
			await this.emailQueue.add('send', { to: user.email, template: 'digest' });
		}
	}
}

// Queue monitoring with Bull Board
import { BullBoardModule } from '@bull-board/nestjs';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';

@Module({
	imports: [
		BullBoardModule.forRoot({
			route: '/admin/queues',
			adapter: ExpressAdapter
		}),
		BullBoardModule.forFeature({
			name: 'email',
			adapter: BullMQAdapter
		}),
		BullBoardModule.forFeature({
			name: 'reports',
			adapter: BullMQAdapter
		})
	]
})
export class AdminModule {}
```

Reference: [NestJS Queues](https://docs.nestjs.com/techniques/queues)
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall