r/nestjs • • 13h ago

Production-Grade Fault Tolerance for TypeScript: Retry, Circuit Breaker, Timeout and Hedging

3 Upvotes

@ylcnfrht/resilience is an open-source resilience library for TypeScript. Retry, circuit breaker, timeout, fallback, hedging and rate limiting are composed into a single pipeline, following the Polly v8 API.

  • Typed errors: unhandled failure modes surface at compile time

  • Deadline propagation across nested calls

  • Integrations for fetch, axios, Express, Fastify, Koa, Hono and NestJS

  • Zero dependencies, from 4.1 KB; runs on Node.js, Bun, Deno, Workers and browsers

Docs: https://resilience.ferhatyalcin.dev

GitHub: https://github.com/ylcnfrht/resilience


r/nestjs • • 1d ago

Looking for a good project-based Node.js/Nest backend course

6 Upvotes

Hey everyone!

So I am a mobile developer with 4 years of experience, so I'm not starting completly from scratch

I'm looking for a practical, project-based course that focuses on building real-world backend applications from scratch to deployment, covering industry best practices.

I'd prefer something beyond beginner-level programming tutorials, with a focus on hands-on development rather than just theory.

Any recommendations based on personal experience? Paid courses are totally fine.

Thanks!


r/nestjs • • 3d ago

Stop passing req.user everywhere: I ported Spring Security's architecture to Express

Thumbnail reddit.com
2 Upvotes

r/nestjs • • 4d ago

Why I'm choosing a modular monolith instead of microservices for my next backend project

Thumbnail reddit.com
8 Upvotes

r/nestjs • • 5d ago

MikroORM Under Heavy Load in Complex Domains (300+ RPS/inst): >30% Event Loop Spent in ORM. Experience, Pitfalls, and Code Review

7 Upvotes

Hi everyone!

I’m looking for real-world experience using MikroORM under solid load. By "heavy load" in this context, I don’t mean trivial services with SELECT 1, but rather systems with complex domain logic (HRM / ERP / IAM) operating on entity graphs, with loads reaching 300+ RPS per single service instance.

The Problem

During load testing, I ran into noticeable overhead caused by the ORM itself. The profiler shows that >30% of the Event Loop time is consumed specifically by MikroORM.

Breakdown by components:

  • ~10% — QueryBuilder, QueryHelper, criteria node parsing;

  • ~10% — EntityManager, SQL driver, shared utilities, and platform type transformations;

  • ~6% — Entity instantiation, hydration, and relationship maintenance;

  • ~3% — The entire Unit of Work block, including Identity Map.

Initial Baseline / Rule-Outs

To eliminate obvious culprits:

  1. Logging: Completely disabled during load testing.

  2. OpenTelemetry: Sampling rate is set to 0.1 and configured so that dropped trace samples do not create unused spans.

As a result, under high RPS, Event Loop Utilization (ELU) and Event Loop lag start spiking rapidly. Even with optimal database performance and zero bottlenecks in the rest of the application code, the ORM overhead severely degrades overall request P99 latency.

Code & Architecture

You can inspect how the ORM is integrated into the service architecture in this repository: example service

I’d appreciate any constructive criticism, highlights of potential bottlenecks in my current usage of EntityManager / QueryBuilder, or advice from anyone who has tuned MikroORM for similar load profiles.

Thanks in advance!


r/nestjs • • 6d ago

Changes regarding the (unofficial) selfhosted nestjs observe version

12 Upvotes

A few days ago I posted this self-hosted collector for @nestjs/observe. The creator of NestJS and NestJS Observe reached out (issue #1) because the name could make people think it is an official project. The repo is now called https://github.com/MontejoJorge/unofficial-selfhosted-nestjs-observe

He also changed the license of the package @.nestjs/observe. Releases after 0.3.20 ship under the NestJS Observe Agent License, which only allows sending telemetry to NestJS Observe. That is his call, but i think its a shame, since earlier he said building your own integrations was fine and now its not allowed.

You can check the demo of my project here https://montejojorge.github.io/unofficial-selfhosted-nestjs-observe/

The latest changes includes the users and releases sections, and a storage page to view how much storage are using the logs, traces and requests of your apps.


r/nestjs • • 8d ago

To framework or not

7 Upvotes

I know rust Axum
Also Aspnet and nestJs

What do you think should i use full framework or barebones like axum

Knowing that we’re a startup and our projects mostly CRUDs

With Axum i gain control the code ,rust strong type system , modern, memory safety and compilation to machine code .
But suffering from no conversions and crates ( packages incompatibilities ) . Although I’m following clean architecture and MVC.

Frameworks like nest or asp you gain conversions testing, and compatibility but not machine code ( for dot net it feels old a bit , verbose and vendor locked for Microsoft to an extent )

Wdyt?


r/nestjs • • 9d ago

Best saas arhitecutre

0 Upvotes

Hey!

We're a small software agency planning a large SaaS platform for public institutions. We've talked to several developers and compared recommendations from different AI models, but we're still getting conflicting opinions on the best tech stack.

We're starting from scratch, with no preferred language or framework. Most development will be done using Claude Code and Codex, with us handling architecture, requirements, and reviews.

What we're building:

500–1,000 institutions (multi-tenant SaaS)

50–80 modules with thousands of features: document management, registries, requests, approvals, workflows, GIS, reporting, etc.

Around 100k public employees and potentially 20–100k citizens using the platform

Hundreds of dynamic forms, complex roles, permissions, and institution-specific configurations

PDF generation, electronic signatures, document archiving, and integrations with government/third-party APIs

A platform-wide AI assistant that can search documents, fill forms, generate files, and execute authorized actions

Web, Windows desktop, Android, and iOS

High availability, strong security, GDPR compliance, and long-term maintainability (10+ years)

Our main questions:

NestJS or FastAPI? Which would you choose for a large modular backend? Does TypeScript across the stack outweigh Python's ecosystem, considering the AI mostly uses external LLM APIs?

React or Angular? Which is better for 80+ modules, complex forms, dashboards, and long-term maintenance?

Mobile: Flutter, React Native, or something else? Ideally, we'd reuse as much code as possible.

Multi-tenancy: PostgreSQL shared schema + RLS, or a separate database per institution? Which scales and maintains better at 1,000 tenants?

Architecture: Modular monolith or microservices? How would you organize modules, dynamic forms, permissions, and external integrations?

AI: Would PostgreSQL + pgvector be enough for RAG and tool calling, or would you introduce a knowledge graph? How would you enforce permissions and prevent prompt injection?

API: REST + OpenAPI or GraphQL for third-party integrations?

AI-assisted coding: How would you structure a monorepo, CI, testing, and code reviews when most code is generated by Claude Code/Codex?

If you were starting this from zero today, what stack would you choose, and what would you avoid?

We're not chasing hype or benchmarks. We want something secure, reliable, scalable, and maintainable by a small team for the next 10+ years.

Would really appreciate advice from people who've built large enterprise or multi-tenant systems.


r/nestjs • • 9d ago

Laravel vs NestJS for a multi-tenant SaaS with AI agents and background jobs?

1 Upvotes

Hello everyone, I’m building a web app for service businesses. It combines CRM, projects, tasks, documents, invoicing, email and calendar. It also has an AI assistant that can take actions on a user’s behalf, with the same permissions and approval rules as the rest of the product.

The web app already runs on next.js and TypeScript, with Supabase for Postgres, auth and storage, and Inngest for background workflows. We’re still early in wiring the product to the database, so I’m weighing three paths for the backend:

* Keep next.js and enforce clearer boundaries around the backend code.
* Keep Next.js for the UI and move the backend into a dedicated NestJS service.
* Keep the React UI and build the backend in Laravel.

The backend needs to serve the web app, a future mobile app, integrations and the AI assistant. Background work includes email and calendar sync, document generation, imports and exports, scheduled reminders and workflows that may pause for approval. The requirements I care most about are workspace isolation, permissions, audit trails and safe retries. If a worker crashes halfway through sending a reminder, a retry shouldn’t send it twice.

Some of our implementation is AI-assisted with Claude Code and Codex. I’m looking for a setup that a small team can review, debug and maintain over several years.

For people who’ve operated something similar in production:

  1. When did a dedicated backend become worth it? What problems did it solve, and what did it add to your day-to-day operations?

  2. If you’ve used Laravel or NestJS on a multi-tenant product, where did its conventions help most? Where did you still need to build your own safeguards?

  3. How do you enforce tenant isolation for background jobs and integrations? What happens if a query forgets the workspace filter?

  4. What has held up for multi-step jobs, retries and approvals? I’d love to hear about failures you actually had to recover from.

  5. If you use AI coding tools heavily, which conventions or automated checks have caught the most mistakes?

Thank you 🙏🏻


r/nestjs • • 10d ago

NestJS DevTools v0.3.1 — A big update to my VS Code extension 🚀

3 Upvotes

Hey r/NestJS!

I previously shared NestJS DevTools, a VS Code extension I built to make everyday NestJS development faster.

I've been working on it quite a bit, and v0.3.1 brings some major improvements:

What's new?

  • 🩺 Provider Health: Detects unregistered Injectable() and

  • Controller() classes, reports problems, and offers quick fixes to register providers in the right module.

  • 🧭 Routes Explorer: Browse all your API endpoints in one place, grouped by controller, with HTTP methods, Swagger tags, and documentation coverage.

  • 💉 Dependency Injection Tools: Find provider usages, automatically inject providers into constructors, and jump to the module that provides them.

  • 📊 API Documentation Coverage: Find endpoints missing ApiOperation() and see your overall documentation coverage.

  • 📝 Smarter Logger: Context-aware log insertion, custom templates, and bulk log cleanup with a preview.

  • ⚡ File Generator 2.0: Generate any NestJS file type, create custom templates, and scaffold matching unit tests.

  • 🎯 Command Hub: Access all extension features from one searchable menu.

The idea is simple: Bring useful NestJS development tools directly into VS Code without extra dependencies, configuration, or changes to your application.

🔗 NestJS DevTools – VS Code Marketplace

I'd genuinely appreciate it if you gave it a try.

What NestJS development task do you think deserves better tooling inside VS Code? I'm actively working on the next release and would love to hear your suggestions.


r/nestjs • • 13d ago

Working on NestJS rules for AI coding agents, and I'd love to learn how you use them in production

7 Upvotes

Hi all,

I'm putting together a set of NestJS best-practice rules that AI coding agents (Claude Code, Cursor, Codex...) can load while working on a project. It's still a work in progress and I'm learning as I go, so I'd really value hearing from people who use NestJS professionally.

If you have a minute, I'd love to know:

- Do you use an AI agent on your NestJS code day to day? Which one, and for what kind of tasks?

- Do you give it any project guidance (AGENTS.md, CLAUDE.md, Cursor rules, skills)? What has actually been useful?

- What does it get wrong most often on NestJS? Things I keep correcting are circular module imports, accidental request-scoped providers and missing validation.

- Is there a convention or pattern from your own production experience that you'd want an agent to always follow?

The project is open source (MIT) and I'm the one building it, in case you want to look at what I have so far: MattiaValerio/nest-skills.
It has 40 rules for now. Any suggestion, correction or "this rule is wrong because..." would help a lot, and I'm happy to credit anyone who contributes.

Thanks for reading!


r/nestjs • • 14d ago

I made a Hono adapter for Nest, on Bun it's ~17% faster than the new platform-node

11 Upvotes

been running nest on bun for rigtch.fm, and the express/fastify adapters there go through bun's node:http compat layer, so i wrote `@mnigos/platform-hono`. it serves nest from Bun.serve on bun and `@hono/node-server` on node, works with nest 11 and 12. on the same hello world benchmark nest used for the platform-node launch (wrk -t4 -c100, nest 12.3.2 for every adapter, M4) it does 141k req/s on bun vs 121k for platform-node on bun. on node it's about fastify level, the gains are on bun

not supported yet: nest versioning, views and express/fastify style `@Res()` calls. if something breaks in your app open an issue https://github.com/Mnigos/platform-hono


r/nestjs • • 15d ago

File structure for monolithic microservices (nx workspace)

Thumbnail reddit.com
0 Upvotes

r/nestjs • • 16d ago

NestJS Devtools

11 Upvotes

Hey everyone,
I made a VS Code extension for NestJS developers to make everyday development faster and easier.

NestJS DevTools includes:

Smart Logger: Quickly insert debug, log, warn, error, and verbose statements with automatic class names.

Module Navigation: Browse your NestJS modules and quickly jump between services, controllers, DTOs, entities, and other files.

File Generator: Generate NestJS boilerplate files with the correct naming conventions and imports.

Method Search: Quickly find and navigate between methods and API routes in your files.

I originally built it to improve my own workflow, and thought other NestJS developers might find it useful too.
I’d love to hear your feedback, suggestions, or ideas for future features!
🔗 NestJS DevTools – VS Code Marketplace


r/nestjs • • 16d ago

Node.js 26 LTS

11 Upvotes

What does the Node.js 26 move to LTS mean for Nest.js?

Will appreciate, if someone could provide an overview / what to expect in Nest


r/nestjs • • 17d ago

Made (AI did) a selfosted version of nestjs observe dashboard.

28 Upvotes

Here is the repo so you can try it! https://github.com/MontejoJorge/selfhosted-nestjs-observe

Works with the @nestjs/observe pacakge.


r/nestjs • • 20d ago

Typed WebSocket gateways for NestJS, with AsyncAPI docs and a generated client

14 Upvotes

Hi all, I want to share a NestJS integration for a WebSocket framework I built, chanx-js. It gives you gateways where every message is typed and validated, documented as AsyncAPI, and the frontend client is generated from those docs.

What pushed me to build it: with @WebSocketGateway I still had to write the client types by hand, there were no docs for the messages, and broadcasting across several instances needed extra setup.

What it gives you:

  • Payloads validated before your handler runs, with Zod, Valibot, ArkType or class-validator DTOs

  • AsyncAPI 3 docs generated from your gateways, served at /asyncapi

  • A typed client generated from those docs, with React, Vue, Svelte and Solid bindings, so a wrong payload fails to compile on the frontend

  • Broadcasts across instances through Redis, and an injectable ChanxService to push to users from any service, controller or queue worker

  • Topics like room:lobby, many of them over one socket

  • Test helpers to send, receive and capture broadcasts

A gateway looks like this:

It's a normal injectable class, so guards, interceptors, pipes and exception filters work as you'd expect. It runs on both Express and Fastify.

Repo: https://github.com/chanx-dev/chanx-js

NestJS guide: https://js.chanx.dev/server/integrations/nestjs

It's still new, so if anything doesn't fit the way you structure Nest apps, please open an issue or a discussion. Stars and PRs are welcome too.


r/nestjs • • 22d ago

🚀 NestJS 12 + Drizzle ORM Starter Template (Production-Ready)

2 Upvotes

I’m sharing a backend boilerplate that I’ve been refining for my own projects and have now decided to release as open source.

The goal was to create a modern, ultra-fast, production-ready core—stripped of the usual overhead—by using Drizzle ORM instead of TypeORM or Prisma.

Tech Stack & Key Features:

- NestJS 12 with TypeScript `6.0.3`.

- Drizzle ORM + PostgreSQL (includes support for migrations, `db:push`, and centralized, filter-based PostgreSQL error handling).

- JWT Authentication: Implements Access & Refresh Token rotation, with tokens stored in the database (hashed via SHA-256) and managed by an automated cleanup task (Cron).

- Security: Includes HTTP-only cookies, Helmet, CORS, CSP, and rate limiting (`@nestjs/throttler`). It also supports sending tokens via JSON or standard `Authorization` HTTP headers for non-web clients (such as mobile apps or other APIs).

- Swagger / OpenAPI: Features an integrated script (`pnpm run generate:types`) that automatically exports TypeScript types for use in frontend applications (React, Svelte, or Vue).

- Structured Logging: Integrated with `nestjs-pino` (plus `pino-pretty` for development).

- Email (Optional): SMTP module using Nodemailer and Handlebars (`.hbs`) templates.

- Testing: Includes unit tests and a comprehensive suite of isolated E2E tests using Jest.

- Docker & Docker Compose: Pre-configured for local development.

GitHub Repository: https://github.com/nasadmidev/nestjs-drizzle-auth-template

Any feedback, pull requests, or stars on GitHub are more than welcome! I hope this helps others jumpstart their own projects.


r/nestjs • • 23d ago

How should I integrate an existing NestJS authentication system with a React + Flowbite React frontend?

2 Upvotes

I'm developing a Grievance Redressal Portal as a learning project. My backend is built with NestJS, TypeScript, Prisma, and PostgreSQL.

I have been implementing authentication (User Sign In and Sign Out) using the "@nestjs/authentication" package of NestJS v12.

I would like to know conceptually the changes to be made to my back end such that I should be able to extend the authentication feature to a React-based front-end.

I have adapted the code by hand from the "Register The Authentication Module" and "Add Sign-Up and Sign-In" sections of the NestJS docs for NestJS v12: Authentication | NestJS - A progressive Node.js framework

I am posting my code here.

NOTE: The authentication system uses server-side sessions managed through nestjs/authentication and a session cookie. The package's SessionCookieProvider reads the cookie and loads the user through the validate() method.

//sign-in.dto.ts
import { PickType } from "@nestjs/swagger";
import { UserUniversalDto } from "../../users/dto/user-universal.dto";
export class SignInDto extends PickType (
    UserUniversalDto,
    ['user_email', 'user_password']
) {};
//credentials.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service.js';
import { CreateUserDto } from '../users/dto/create-user.dto.js';
import { FindUserByEmailDto } from '../users/dto/find-user-by-email.dto.js';
import * as argon2 from 'argon2';
import { USER_STATUS } from '../users/user.constants.js';

u/Injectable()
export class CredentialsService {
  constructor(
    private readonly usersService: UsersService
  ) {}

  async register(createUserDto: CreateUserDto) {

    const findUserByEmailDto: FindUserByEmailDto = {
      user_email: createUserDto.user_email
    }

    // Don't create the user if the email already exists.
    if (await this.usersService.findUserByEmail(findUserByEmailDto)) {
      throw new ConflictException('Email already registered. User already exists.');
    }
    // The address is unverified: anyone can type any email into a sign-up form.
    const registered_user = await this.usersService.createUser(createUserDto);
    return registered_user;
  }

  /** The user, or null when the email or the password is wrong. */
  async verify(email: string, password: string) {
    
    const findUserByEmailDto: FindUserByEmailDto = {
      user_email: email
    }

    const found_user = await this.usersService.findUserByEmail(findUserByEmailDto);
    
    // Checking if the user exists.
    if (!found_user) {
      throw new ConflictException('User does not exist. Login rejected.');
    }
    
    // If the user is suspended, reject login by throwing an exception.
    if (found_user.user_status === USER_STATUS.SUSPENDED) {
       throw new ConflictException('User is suspended. Login rejected. Please contact admin.');
    }

    // If the found_user's password is wrong, (password_hash doesn't match) then the it should return null.
    const password_hash: string | null | undefined = found_user?.user_password;
    
    const password_check = await argon2.verify(password_hash as string, password);

    // Checking if the user's password is correct.
    if (password_check !== true) {
      throw new ConflictException('Incorrect username or password. Login rejected.');
    }

   
    return found_user;
  }
}

//myauthentication.controller.ts
import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, SignInService } from '@nestjs/authentication';
import { SignInDto } from './dto/sign-in.dto';
import { CredentialsService } from './credentials.service';
import { CreateUserDto } from '../users/dto/create-user.dto';

()
('auth')
export class MyAuthenticationController {
  constructor(
    private readonly credentialsService: CredentialsService,
    private readonly signInService: SignInService,
  ) {}

  ('sign-up')
  async signUp(@Body() createUserDto: CreateUserDto) {
    const user = await this.credentialsService.register(createUserDto);
    var string_user_id = String(user.user_id);
    await this.signInService.signIn(string_user_id, { method: 'password' });
    return user;
  }

  ('sign-in')
  (200)
  async signIn(@Body() signInDto: SignInDto) {
    const user = await this.credentialsService.verify(signInDto.user_email, signInDto.user_password);

    var string_user_id = String(user.user_id);

    const { session } = await this.signInService.signIn(string_user_id, { method: 'password' });
    return { mfaRequired: session.mfa === 'pending' };
  }

  ('sign-out')
  (204)
  async signOut() {
    if (!(await this.signInService.signOut())) {
      throw new UnauthorizedException();
    }
  }
}

//myauthentication.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module';
import { SessionAuth } from './session-auth.provider';
import { MyAuthenticationController } from './myauthentication.controller';
import { CredentialsService } from './credentials.service';

({
  imports: [UsersModule],
  controllers: [MyAuthenticationController],
  providers: [SessionAuth,
    CredentialsService
  ]
})
export class MyAuthenticationModule {}

//session-auth.provider.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, SessionCookieProvider, type SessionRecord } from '@nestjs/authentication';
import { UsersService } from '../users/users.service.js';

import type { User as PrismaUser } from '../generated/prisma/client.js';
export type User = Omit<PrismaUser, 'user_password'>;

u/Injectable()
export class SessionAuth extends SessionCookieProvider<User> {
  constructor(
    private readonly usersService: UsersService,
    registry: AuthenticationRegistry,
  ) {
    super();
    // Adds this provider to the chain the guard runs for every request.
    registry.registerProvider(this);
  }

  // Called for every request with a live session cookie.
  // Returning null (the user was deleted) ends the session.
  validate(session: SessionRecord) {
    console.log("In validate() in SessionAuth")
    const user_id = session.userId; 
    var numeric_user_id = Number(user_id);
    return this.usersService.findOneUser(numeric_user_id);
  }
}

r/nestjs • • 23d ago

Need help on the approach to authentication I should use for my mobile app

2 Upvotes

I am developing a mobile app, which has a react native frontend, nest.js as the backend and for db and authentication, I'm planning to use supabase.

Now, currently as my app is in its initial stages I'm planning to use the supabase, as it free tier provides ample limits for my use case.

However, in later years if my app grows. I may think of switching to a cheaper alternative.

So, what I am planning to follow is for authentication, route the requests to my backend and inturn the backend will communicate with the supabase to authenticate the user. The backend will save the supabase token, create a separate session token for the user and send it back to the user.

My main reason for doing this is, I want the authentication to be provider independent and any changes needed should be done on the backend instead of the app.

Please let me know, if this approach is correct. What are the pros and cons. How much effort it would require to implement this. Will the security concerns increase if my backend starts handling this instead of the supabase only.

I also want to integrate the google and apple login as well. How will this approach affect it?

Also, if there any other better approaches, please let me know.


r/nestjs • • 25d ago

Is TypeORM still a reasonable choice for a serious NestJS + Postgres backend, or should I migrate to Drizzle/Prisma now?

15 Upvotes

Hi everyone,

I’m a solo developer building a SaaS backend with NestJS, PostgreSQL and TypeORM. It’s already fairly advanced (around 30 entities, including some reporting features), and it has only a few users for now. A migration would be costly, but not impossible, and I’d rather decide now than when I have a lot more users and data.

I haven’t hit any major blockers with TypeORM so far. What worries me is what I keep reading: concerns about maintenance, type safety gaps, quirks with relations and migrations, while Drizzle (and Prisma) get a lot of praise. I’m leaning towards Drizzle if I migrate, but I’m not sure how much of the hype applies to a real-world project like mine.

My questions:

  1. Is TypeORM a reasonable choice for a serious, long-lived production app? If you’ve run it in production, what problems did you actually run into, if any?

  2. If you migrated away from it (to Drizzle, Prisma, Kysely, MikroORM...), was it worth it? What did you gain, and what did the migration really cost you?

  3. Performance: I’ve seen benchmarks showing Drizzle being much faster. For a typical SaaS workload (mostly CRUD plus some report queries), does the ORM overhead matter in practice, or is the real bottleneck almost always the queries, indexes and schema design?

Since I’m working alone, maintainability and long-term support matter a lot to me. I don’t want to end up stuck with a tool that gets abandoned or that fights me as the project grows.

I’m not looking for a “X is the best” answer, just real-world experiences and trade-offs, especially from people who’ve used these in production. Thanks in advance!


r/nestjs • • 26d ago

Webhook Reliability & Idempotency Trade-offs: Architecture Review of Relay

Thumbnail
reddit.com
3 Upvotes

Feel free to share your experiences, critique the current code, or submit focused PRs !


r/nestjs • • 27d ago

Our IoT KPI endpoint went from 17s to 240ms

8 Upvotes

We collect telemetry from industrial machines: fuel consumption, engine hours, idle time, and more. Our ingestion stack uses Python, NestJS, a queue, and PostgreSQL.

As the readings table grew, one dashboard endpoint started taking around 17 seconds.

A few things helped us bring it down:

  • SQL optimization: Replaced repeated LATERAL lookups with window functions. Query time dropped from 5.6s to 150ms.

  • Precomputed shift metrics: Stopped recalculating completed shifts on every request. Late-arriving telemetry is handled through backfills.

  • Request deduplication: Concurrent identical requests now share one computation, with a short-lived cache for successful results.

  • Background refresh: Serve cached data while refreshing expired entries. The dashboard response dropped to around 240ms.

  • Monthly partitioning: Partition by ingestion time because machines sometimes upload historical readings after reconnecting.

The biggest lesson for me was to look at what the database was repeatedly doing before reaching for caching. Fixing that made the biggest difference.

Curious how others handle late-arriving telemetry when maintaining time-series aggregates.

Note: I used AI to help polish the wording, but I’m sharing the technical details and lessons for discussion.


r/nestjs • • 28d ago

Handling @Cron() across multiple NestJS pods without BullMQ or Redis locks (Postgres, Redis, RabbitMQ, NATS)

7 Upvotes

When scaling a NestJS app to multiple pods, @nestjs/schedule runs every @Cron() and @Interval() handler inside every replica.

The usual workarounds are moving everything into BullMQ repeatable jobs or wrapping handlers in a Redis lock, which is awkward when a NestJS service only runs on PostgreSQL (or RabbitMQ / NATS) and doesn't otherwise need Redis.

Another pattern is slot-based coordination over the datastore the service already uses (anarchon on npm), where replicas compete to claim each scheduled UTC slot atomically. On PostgreSQL, Redis/Valkey and SQLite the winner also renews a lease while the handler runs, so if a pod stops during a rolling deploy (SIGTERM) or crashes (OOMKilled), another replica takes over the slot. RabbitMQ and NATS only pick the winner: if that pod dies, the run is lost, with no takeover or catch-up.

A slot can also be skipped (the previous run is still going, a pod is too late, every pod was down), so the handler works on everything still pending instead of treating its slot as the only chance. A skipped tick then delays the sync instead of leaving a gap:

import { Injectable } from '@nestjs/common';
import { Cron, Every, type JobContext, Scheduled } from 'anarchon';

@Injectable()
@Scheduled()
export class ReportsService {
  constructor(private readonly customers: CustomerSync) {}

  @Every('sync-customers', '30s')
  async sync(ctx: JobContext) {
    // everything not synced yet, not only "this 30s window"
    for (const customer of await this.customers.pending()) {
      ctx.signal.throwIfAborted();
      await this.customers.push(customer); // safe to repeat
    }
  }

  @Cron('weekday-digest', '0 8 * * 1-5', { timezone: 'Europe/Athens' })
  async digest(ctx: JobContext) {
    // ...
  }
}

Or without method decorators, registering on the injected Scheduler in onModuleInit:

this.scheduler.cron('monthly-invoices', '0 6 1 * *', (ctx) => this.buildInvoices(ctx));

How are you handling recurring cron jobs in multi-pod NestJS setups when you aren't already running Redis/BullMQ?

NestJS setup guide: https://aristoteliss.github.io/anarchon/recipes/nestjs/

Open to feedback and questions!

Edit: added which backends get takeover, and changed sync-customers to sync everything pending (thanks u/GetPingcron).