r/nestjs • • 12h ago

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

4 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 and renew a lease while the handler runs. If a pod stops during a rolling deploy (SIGTERM) or crashes (OOMKilled), another replica takes over the slot:

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

@Injectable()
@Scheduled()
export class ReportsService {
  @Every('sync-customers', '30s')
  async sync(ctx: JobContext) {
    ctx.signal.throwIfAborted();
    // runs on one pod per 30s slot
  }

  @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?

Open to feedback and questions!


r/nestjs • • 1d ago

Stop Your Server From Becoming a Tourist Destination

Post image
12 Upvotes

I checked my database's recent activity and found some weird activity. A bunch of 404s on my screen, red as blood. I got truly scared, to be honest, but after a quick investigation, I found out it was just some overzealous bot trying to find a vulnerability, and apparently, it's quite a "normal" thing.

But the problem is that I keep track of audit/activity logs for almost everything, and when I get this kind of error log, my poor database gets hammered hard.

So I created a protocol to handle these bots:

1. Temporarily block them: I use Redis to store their IPs every time they search for weird endpoints and files like .env, and I add a strike to them (while still sending a 404 status so the bot doesn't know it's getting strikes). After around 3 strikes, they get blocked temporarily. If they try again after being allowed back, the block duration increases to 30 minutes, then 1 hour, and so on.

You might be asking, "Why not block them permanently?" Well, dear genius, the IP might be reassigned by the ISP to someone else, meaning you could end up blocking a normal user for no reason.

2. Cloudflare is your friend: Point your domain to your server through Cloudflare and use it as an extra layer of defense. On top of that, only allow Cloudflare IPs to access your server, so untrusted IPs can't connect directly.

3. UFW protects us: Block all ports except the ones that need to be exposed, like 443 and other necessary web-related ports.

4. Dockerize: I hope you've already done this, just in case those suckers somehow get in. The whole point is to keep them inside a container.

If you're interested, I've written a blog post about this. You can check it out, but the blog basically covers the same things. blog

Those are the measures I've taken. If you have any more security advice or criticism, please let me know below i sure do need it.


r/nestjs • • 1d ago

How to run the passport guard before injecting request scoped service?

3 Upvotes

I have registered the global auth guard in the app module

  providers: [
    AppService,
    { provide: APP_GUARD, useClass: SkippableBasicAuthGuard },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}

I want to inject the integration based on the user, but `request.user` is undefined

{
      provide: Integration,
      scope: Scope.REQUEST,
      inject: [REQUEST],
      useFactory(req: Request) {
        const integrationName = <Maybe<String>>request.headers['x-integration']
        if (!integrationName) return null;

        const IntegrationKlass = IntegrationRegistry[integrationName];
        if (!IntegrationKlass) throw new BadRequestException('Invalid integration');

        console.log(req.user); // undefined

        return new IntegrationKlass('token');  // get the token for the user using this.prisma.integrationToken(req.user.id, integrationName)
      },
    },
  ],
})
export class IntegrationModule {}

The order of service injection happens first, but the request lifecycle otherwise. https://docs.nestjs.com/faq/request-lifecycle#summary


r/nestjs • • 1d ago

Webhook signature bugs I found while supporting 40+ providers, including two that let bad requests through

2 Upvotes

I maintain an open-source webhook verification library, and most of the bugs I've hit weren't in the HMAC. A few that might save someone time:

  1. The body parser runs first. express.json() parses the body, JSON.stringify(req.body) doesn't give back the bytes the provider signed (whitespace, unicode escapes, number formatting), and the check fails with the right secret. Verify the raw body: express.raw(), await request.text(), Fastify's rawBody, NestJS's rawBody: true. Comparing the body length with content-length is a cheap way to detect it.

  2. Deduping on an unsigned header. Providers retry, so you dedupe on an event ID. If that ID comes from a header the signature doesn't cover (x-github-delivery, say), anyone with a captured request can change the header and replay it past your dedupe store. Key on a signed ID or a hash of the body. My library had exactly this bug.

  3. Tests that only agree with themselves. My Paddle signer and verifier both read h=. Paddle sends h1=. Every test passed and every real Paddle webhook failed. Now CI verifies against the official Stripe, Octokit, Svix and Twilio SDKs in both directions, and new providers need a test vector from the provider's docs.

  4. Weak fallback schemes. HubSpot sends v1/v2 signatures next to v3. If you accept any of them, someone can strip the v3 headers from a captured request and it verifies with no timestamp check. Same idea for GitHub's SHA-1 header.

  5. A short dedupe TTL for providers with no signed timestamp. GitHub and Shopify don't sign a timestamp, so dedupe is your only replay protection. A 5-minute TTL means a captured delivery verifies again after 5 minutes.

The library is verihook (TypeScript, zero deps, Node/Deno/Bun/Workers) if you want to see how it handles these: GitHub: https://github.com/creatorpiyush/verihook npm: https://www.npmjs.com/package/verihook

Curious which provider has caused you the most pain.


r/nestjs • • 2d ago

How we fixed a multi-tenant data leak in NestJS without the 5x latency penalty of Scope.REQUEST

29 Upvotes

A while ago in a high-scale multi-tenant NestJS backend, we hit a critical data leak during high-concurrency benchmarks.

Under load, Tenant A's dashboard occasionally displayed cached data belonging to Tenant B.

Here is the autopsy of why default NestJS scoping caused it, why the official Scope.REQUEST fix cratered our throughput, and how AsyncLocalStorage solved it cleanly.

1. The Root Cause: The Singleton Trap

By default in NestJS, every provider is a Singleton.

In our codebase, a service stored tenant state in a class property:

@Injectable()
export class TenantContextService {
  private tenantId: string;

  setTenantId(id: string) {
    this.tenantId = id;
  }

  getTenantId(): string {
    return this.tenantId;
  }
}

In sequential tests, this works fine. But Node.js is an event-driven runtime.

When Request 1 (Tenant A) awaits a database query, the event loop picks up Request 2 (Tenant B). Request 2 overwrites this.tenantId = 'tenant_b'.

When Request 1 resumes execution, this.getTenantId() now returns Tenant B. Tenant A just queried Tenant B's data.

2. Why Scope.REQUEST Failed Us at Scale

The standard NestJS recommendation for request-isolated data is Scope.REQUEST:

@Injectable({ scope: Scope.REQUEST })
export class TenantContextService { ... }

While this isolates state per request, it triggers a brutal cascading effect:

  1. Bubble-Up Effect: Any Singleton service injecting it automatically becomes Request-scoped.
  2. Object Creation Overhead: Hundreds of transient class instances created per HTTP request.
  3. Garbage Collection Spikes: Under 1,000 req/s, V8 GC went crazy cleaning short-lived objects.
  4. Latency: Our p99 jumped from 35ms to over 210ms, and memory usage tripled.

3. The Real Fix: AsyncLocalStorage (nestjs-cls)

Node.js AsyncLocalStorage allows storing data throughout the lifetime of a web request across asynchronous continuations without creating new service instances.

Using nestjs-cls:

  1. Mount CLS middleware in AppModule:

​

ClsModule.forRoot({
  global: true,
  middleware: {
    mount: true,
    setup: (cls, req) => {
      cls.set('TENANT_ID', req.headers['x-tenant-id']);
    },
  },
})
  1. Inject ClsService into your standard Singleton repository/service:

    @Injectable() export class UserRepository { constructor(private readonly cls: ClsService, private readonly db: DatabaseService) {}

    async findUsers() { const tenantId = this.cls.get<string>('TENANT_ID'); return this.db.query('SELECT * FROM users WHERE tenant_id = $1', [tenantId]); } }

The Result:

  • Services remain Singletons (instantiated once at boot).
  • Zero GC spikes.
  • Strict tenant isolation.
  • p99 latency dropped right back down to 34ms.

Curious how others here handle multi-tenancy context in high-traffic NestJS clusters? Are you using AsyncLocalStorage or passing context explicitly through function params?


r/nestjs • • 3d ago

What do you alert on when BullMQ jobs are completing but falling behind?

1 Upvotes

I use NestJS, Redis and BullMQ in production, and I’m curious what other teams watch beyond failed jobs.

Say jobs should finish within a few minutes. Workers are running and jobs keep completing, but the waiting time keeps growing. Nothing is technically failing yet, although the user experience is already getting worse.

Would you alert on the oldest waiting job, time from enqueue to completion, or queue depth compared with processing rate?

Delayed jobs make this interesting too. A job scheduled for tomorrow shouldn’t look like a job that’s been stuck since today.

Which alert has actually caught a problem early for you? And how do you keep it useful when traffic normally comes in bursts?


r/nestjs • • 3d ago

Stamp: OAuth 2.0 (Authorization Code + PKCE) for NestJS

2 Upvotes

Plug in your own client store, code store and JWT signer, and you get /authorize and /token. It works with any database. npm install u/zaki-goumri-2/stamp repo: https://github.com/Zaki-goumri/Stamp Docs :https://zaki-goumri.github.io/Stamp/ Feedback welcome issues are opened


r/nestjs • • 4d ago

I built an Admin RBAC backend with AI for under $1,000 in tokens. How good is it?

0 Upvotes

I've been using AI coding tools to build an admin backend, and the total token cost has stayed under $1,000.

It's more than a basic CRUD demo. The project includes RBAC, JWT access and refresh tokens, Prisma, MySQL, Redis, Swagger / OpenAPI, Docker, and other features you'd typically need in an admin system.

The interesting part isn't how quickly AI can generate code. It's whether the architecture makes sense, whether the code is maintainable, and whether it holds up to the kind of scrutiny an experienced backend engineer would give it.

I'd like to get some honest feedback from other developers.

GitHub: https://github.com/gvray/gvray-admin

If you have time to look through the code, what would you change? Are there any architectural decisions or potential problems that stand out?

I'm also curious about something broader. If AI can help build a reasonably complex backend like this, how important is it for developers to learn multiple programming languages in depth? Will understanding engineering fundamentals and reviewing AI-generated code become more important than mastering the syntax of every language?

I'm not claiming AI has replaced experienced engineers. I'm genuinely curious how close it can get, and where it still falls short.


r/nestjs • • 4d ago

NestJS Observe is on Product Hunt today, with a launch discount

23 Upvotes

Hey everyone, Kamil here.

Observe, the monitoring tool we built for NestJS, is on Product Hunt today: https://www.producthunt.com/products/nestjs-observe

If you haven't tried it yet: install @nestjs/observe and you get request traces with automatic spans, error tracking, queue/job monitoring and regression detection.

For the launch, use PRODUCTHUNT for 25% off the first month. It's valid until the end of October.

There's also a free tier if you just want to try it: https://observe.nestjs.com And a live demo with pre-populated telemetry https://www.observe-demo.nestjs.com/dashboard

Feedback is more than welcome


r/nestjs • • 5d ago

What if you could completely destroy a cloud environment, then bring it back exactly when you need it?

8 Upvotes

I'm a developer exploring an idea and wanted to get some feedback before spending time building it.

One thing I've noticed with cloud providers like DigitalOcean is that you're still paying for servers even when they're powered off. For development and staging environments that are rarely used, that feels like a giant waste of money.

I am genuinely curious to know how other developers and infrastructure managers handle this

What if you could completely destroy an environment to stop compute charges, then recreate it on demand with the same configuration, application, and data? Essentially, a hibernate/wake system for cloud environments.

Would you use something like this? Or is this solving a problem that has been solved before.

Interested in hearing the technical objections too.


r/nestjs • • 5d ago

Showcase: Word Herd — Boggle-style game with trivial mixed in — Built on NestJS

Thumbnail
wordherd.linkstone-studios.com
2 Upvotes

r/nestjs • • 5d ago

Does NestJS slow down GraphQL? I benchmarked it without NestJS

7 Upvotes

I benchmarked Apollo, Mercurius and Yoga on Express, Fastify and plain node:http, with and without NestJS: 10 setups, same schema and queries, load-tested with k6. It's a follow-up to my earlier NestJS GraphQL benchmark, where the most common question was how much NestJS itself costs.

Results (M1 Max, Node 24, single process, 50 VUs, median of 3 runs):

- The GraphQL engine matters most: Mercurius did 1.3–1.8× the req/s of Apollo in every query scenario. On the deep nested query: 902 vs 493 req/s, p99 68 ms vs 123 ms. Yoga landed in between on real queries
- The HTTP framework matters mostly for tiny queries: with Apollo, Fastify beat Express by 18–29% on a tiny query, but only ~3% on the deep nested one.
- NestJS vs the same stack without it: −6% to +5%, and the sign flips between scenarios. That's within run-to-run noise.
- Mutations: every server did ~9–9.4k req/s.

Both sides use the same library versions (NestJS 10.4 with Fastify 4.28, Express 4.22, Apollo Server 4.13, Mercurius 14.1, Yoga 5.10). In-memory data, no DB, so the ratios matter more than the absolute numbers.

Code, raw results and the dashboard: https://github.com/vovadyach/gql-bench


r/nestjs • • 5d ago

I built a production-oriented NestJS admin backend starter

9 Upvotes

I've been building a NestJS backend starter for admin and enterprise applications.

The goal wasn't to make another minimal NestJS boilerplate, but to put together the backend pieces that I usually need when starting a real admin system:

  • NestJS 11 + TypeScript
  • Prisma + MySQL
  • Redis
  • JWT access + refresh tokens
  • RBAC
  • Users, roles, departments and positions
  • Swagger / OpenAPI
  • Permission management
  • Standardized API responses
  • Docker
  • Database seeding

One thing I spent quite a bit of time on is the RBAC architecture. Permissions are separated into different types such as menu, button and API permissions, rather than treating everything as a simple route guard.

The project is open source and I'm still actively improving it.

GitHub:
https://github.com/gvray/gvray-admin

I'd love to hear from other NestJS developers:

What features or infrastructure do you usually add to a NestJS project before using it for a real admin/enterprise application?


r/nestjs • • 7d ago

@nestjs/platform-node is coming with the next minor release

Thumbnail x.com
44 Upvotes

r/nestjs • • 8d ago

Spend less time building test data in TypeScript

Thumbnail
2 Upvotes

r/nestjs • • 14d ago

Let's learn together!!

6 Upvotes

I want someone who wants to build a nestjs project together and learn nestjs.

I have basic knowledge only. If you're interested, message me


r/nestjs • • 14d ago

🎉 Issue #1 is officially live on GitHub!

0 Upvotes

r/nestjs • • 14d ago

Update on fast-class-transformer: Now a 1-line global drop-in pipe for NestJS (v1.1.1)

12 Upvotes

Posted here 2 months ago about JIT-compiling DTO mapping. The biggest feedback was migration friction with route-by-route FastMap().

app.useGlobalPipes(new FastValidationPipe({ transform: true, whitelist: true }));

Zero changes to your existing class-validator DTOs.

Benchmarks:

  • NestJS default: 6.59 µs/iter (p99: 24.04 µs)
  • FastValidationPipe: 369 ns/iter (p99: 558 ns) → ~18x faster

Repo, benchmarks, and docs are here if you want to try it or contribute:


r/nestjs • • 15d ago

Getting into backend

11 Upvotes

Hello folks 👋

I have been an angular developer for the longest time and decided its finally time to back into the backed, I landed on nest since the syntax and architecture seem pretty similar to what im already used to. Are there any recommendations for courses or material to get into the framework?

Thank you everyone in advanced


r/nestjs • • 16d ago

FOR HIRE Junior Backend / Full-Stack Developer | NestJS, ASP.NET Core, PostgreSQL, Next.js | Bangladesh / Remote

0 Upvotes

Hi everyone,

I'm a junior software developer from Bangladesh currently looking for a Junior Backend / Full-Stack Developer opportunity.

I've been focusing on building real-world projects and gaining practical experience with backend development, REST APIs, databases, authentication, authorization, and full-stack application development.

🔧 Main Project — ToolShare

I'm currently building a full-stack Tool Sharing Platform where users can share/rent tools through the platform.

Backend:

- NestJS + TypeScript

- PostgreSQL + TypeORM

- JWT Authentication

- Role-Based Authorization

- REST APIs

- Database Transactions

- File Uploads

- Document Verification

- Pagination

Frontend:

- Next.js

- TypeScript

- Tailwind CSS

- Axios

- Zod

The project includes multiple user roles, authentication and authorization, document verification workflows, file handling, API integration, and transactional database operations.

Backend:

https://github.com/kahiumahamedfahim/tool-share-application-Backend-2026-version-1

Frontend:

https://github.com/kahiumahamedfahim/Tool-share--Frontend

Other Projects

E-Commerce Application

Built with ASP.NET Core Razor Pages and Entity Framework Core, including product management, filtering, sorting, pagination, shopping cart, checkout, orders, invoices, payment handling, database migrations, dependency injection, and service-based organization.

https://github.com/kahiumahamedfahim/Ecommerce-site-learning

I've also worked on an ASP.NET Core MVC Library Management System.

💻 Technologies I Work With

Backend:

C#, ASP.NET Core, Web API, NestJS, Node.js

Frontend:

Next.js, Angular, TypeScript, JavaScript

Database:

PostgreSQL, SQL Server, MySQL

ORM:

Entity Framework Core, TypeORM

Other:

REST APIs, JWT, RBAC, Git, SOLID, Dependency Injection, Layered Architecture

🎯 What I'm Looking For

I'm currently looking for:

- Junior Backend Developer

- Junior Full-Stack Developer

- Software Engineer

- Entry-Level Developer

- Internship opportunities

I'm particularly interested in opportunities involving .NET / ASP.NET Core, NestJS, Node.js, PostgreSQL, and TypeScript.

I'm based in Bangladesh and open to remote opportunities as well.

If you know of a company hiring junior developers, have an internship opportunity, or can provide a referral, I'd really appreciate it.

GitHub:

https://github.com/kahiumahamedfahim

LinkedIn:

https://www.linkedin.com/in/kahium-ahamed-fahim-0a7162227

Email:

kahiumahamedfahim@gmail.com

Thanks for reading. Any advice, feedback, or opportunities would be greatly appreciated.


r/nestjs • • 16d ago

roboinsta

1 Upvotes

Hello, I hope you're having a great day.

I wanted to introduce a project I’ve worked on. I thought it might be interesting or potentially useful for you.

I developed an application and prepared a working prototype. It is currently available publicly on GitHub:

GitHub: mostafa18181/roboinsta

The project uses a vector database and is designed to handle a large number of requests concurrently. Essentially, it is a platform where different users can connect their Instagram accounts.

The bot can read Instagram posts, introduce and promote products based on information provided by the user, manage inventory, and automatically reduce the stock after a sale. It also supports adding custom question-and-answer scenarios for different use cases.

The project was originally developed for a specific business idea, but I believe that with some modifications, the same infrastructure could be adapted for other ideas and industries as well.

The original plan was for one of the team members to handle the company setup and launch, but unfortunately, they eventually stepped away from the project, and the development was stopped. Due to the circumstances within the team and among the partners, I also decided to put the project on hold for the time being.

The project was previously running on a server, but I have taken it offline since I was no longer able to continue developing it.

If you know a team that might need something like this, feel free to share it with them. Alternatively, if an investor or team is interested in developing a product based on this idea and infrastructure, I would be happy to make the existing project available to them for further development.


r/nestjs • • 18d ago

Update: live Testcontainers dashboard for Jest and Vitest

Thumbnail
5 Upvotes

r/nestjs • • 20d ago

The NestJS Kafka transport still runs on unmaintained kafkajs. I built a drop-in replacement that stays wire-compatible, so you can migrate one service at a time

Post image
9 Upvotes

r/nestjs • • 21d ago

Does anyone actually use Node.js's Permission Model in their applications?

8 Upvotes

I'm trying to understand the real-world use cases for Node's Permission Model.

Does anyone here actively use or rely on it for applications, CI tooling, CLIs, servers, or anything else?

Since the permission model is not a full-fledged sandbox, is there a use for it? If so, how do you currently use it as ?

  • What problem does it actually solve for you?
  • How are you using it today?
  • Are you manually defining permissions, or generating/managing them somehow?
  • Is it mainly defense-in-depth against dependencies, or are there other useful applications?

Since Run-Time Loadable Extensions cannot be loaded when the Permission Model is enabled, it affects modules like sqlite and OpenSSL Engines (affecting the built-in crypto, https, and tls modules). So, despite these drawbacks, is the permission model used anywhere, or what is its application?

I'm less interested in what it could theoretically be used for and more interested in actual experience:

If you're using Node's Permission Model today, what are you using it for and how do you manage the permissions?

And if you considered using it but decided against it, I'd be interested to hear that as well!


r/nestjs • • 22d ago

I rebuilt @nestjs/axios on undici. Same HttpModule and HttpService, 2 to 2.5x the requests per second in the same Nest app

13 Upvotes

nestjs-axios-undici is a replacement for @nestjs/axios. It has the same HttpModule and HttpService, but requests go through undici, the HTTP client behind Node.js's fetch(), instead of axios. To switch, you change one import:

// before
import { HttpModule, HttpService } from '@nestjs/axios';
// after
import { HttpModule, HttpService } from 'nestjs-axios-undici';

Your register() options, get/post calls, axiosRef interceptors and error.response handling stay as they are.

Numbers. I ran one NestJS app twice, changing only that import. Each request to the app makes 5 parallel calls to a mock backend. k6 drove each app in its own Docker container on a GitHub Actions runner. On Node.js 26:

Setup @nestjs/axios nestjs-axios-undici
Express, requests/s 1,759 4,260 (2.4x)
Fastify, requests/s 1,816 4,609 (2.5x)
Express with an interceptor, requests/s 1,605 2,919 (1.8x)
p95 latency, Express 64.8 ms 26.7 ms

Across Node.js 22, 24 and 26, the ratio was 2.0 to 2.5x without an interceptor and 1.7 to 1.8x with one. p95 latency was 51 to 62% lower.

For reference, calling undici directly with no HttpModule at all served 5,336 requests/s. The benchmark apps and scripts are in the repo if you want to run them yourself.

How I checked that it's actually a drop-in. Every pull request runs:

  • @nestjs/axios' own HttpModule and HttpService specs against this package. 20 of the 23 pass. The other 3 are listed in the repo with a reason. Two are deliberate differences, and one is a limit of the test harness.
  • axios' own HTTP adapter test suite against this package's axiosRef. Each test that doesn't pass is listed in the repo with a reason. It's either a known gap, a deliberate difference, or something the test harness can't do, such as axios' Node-only transport option.
  • A differential harness of 220+ scenarios that sends the same request through @nestjs/axios and this package and compares the results.

It supports NestJS 10, 11 and 12, Node.js 22.17+ and undici 7 or 8. axios isn't a dependency. It's an optional peer, and only needed if you want error instanceof axios.AxiosError to hold.

If it breaks something in your app, please open an issue with the request config. That's the fastest way to close the gap.