Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 42 ยท Practice and Review

Exercises: Advanced Patterns

Practice advanced NestJS patterns: dynamic modules, interceptors, database transactions and retrying job queues, with solutions and runnable stand-ins.

The first exercise set covered the building blocks. This one covers the patterns that show up in real services: configurable dynamic modules, interceptors that reshape responses, transactions that keep data consistent, and queues that retry work.

Each exercise has a task, a read-only Nest solution and a runnable stand-in written for Node 24. The stand-ins are not Nest: they rebuild the idea with a few lines of plain code, using only the standard library (node:sqlite stands in for the database), so you can watch the behavior and then compare it with the Nest code.

Four advanced exercises

Dynamic module forRoot and forRootAsync.
Interceptor Wrap, time and time out.
Transaction All changes or none.
Queue Retry with backoff, once only.

Attempt each task before opening its solution.

1 / 2

Exercise 1: a configurable MailModule

Task. Write a MailModule with forRoot(options) for fixed settings and forRootAsync() for settings that come from another provider (such as a config service). MailService must read its options through an injection token.

Solution (Nest, read-only)
TypeScript
export const MAIL_OPTIONS = Symbol('MAIL_OPTIONS');

@Injectable()
export class MailService {
  constructor(@Inject(MAIL_OPTIONS) private readonly options: MailOptions) {}
  send(to: string) { /* use this.options.host */ }
}

@Module({})
export class MailModule {
  static forRoot(options: MailOptions): DynamicModule {
    return {
      module: MailModule,
      providers: [{ provide: MAIL_OPTIONS, useValue: options }, MailService],
      exports: [MailService],
    };
  }

  static forRootAsync(opts: {
    imports?: any[];
    inject?: any[];
    useFactory: (...args: any[]) => MailOptions | Promise<MailOptions>;
  }): DynamicModule {
    return {
      module: MailModule,
      imports: opts.imports ?? [],
      providers: [
        { provide: MAIL_OPTIONS, useFactory: opts.useFactory, inject: opts.inject ?? [] },
        MailService,
      ],
      exports: [MailService],
    };
  }
}

A dynamic module is just a function that returns a module description. The stand-in below resolves two such descriptions with a tiny container that supports async factories.

Exercise 2: an envelope, a clock and a timeout

Task. Write an interceptor that wraps every successful result as { data, meta: { ms } }, and a second one that fails the request with 408 when the handler takes too long.

Solution (Nest, read-only)
TypeScript
@Injectable()
export class EnvelopeInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    const started = Date.now();
    return next.handle().pipe(
      map((data) => ({ data, meta: { ms: Date.now() - started } })),
    );
  }
}

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      timeout(5000),
      catchError((err) =>
        err instanceof TimeoutError
          ? throwError(() => new RequestTimeoutException())
          : throwError(() => err),
      ),
    );
  }
}

Interceptors wrap the handler like layers of an onion: the first one in the list is the outermost. The stand-in uses promises instead of RxJS and a fake clock, so its numbers are always the same.

Node.js Exercises 1-2: dynamic modules and interceptors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both descriptions go through the same container. The container needs await because the async factory has to finish before MailService can be built, which is the reason forRootAsync exists.

Exercise 3: a transfer that never half-happens

Task. Write transfer(from, to, amount) that moves money between two accounts and records a ledger line. If anything fails, such as insufficient funds, nothing may be saved, not even the ledger line.

Solution (Nest with TypeORM, read-only)
TypeScript
@Injectable()
export class TransfersService {
  constructor(private readonly dataSource: DataSource) {}

  transfer(fromId: number, toId: number, amount: number) {
    return this.dataSource.transaction(async (manager) => {
      const from = await manager.findOneOrFail(Account, {
        where: { id: fromId },
        lock: { mode: 'pessimistic_write' },
      });
      const to = await manager.findOneOrFail(Account, {
        where: { id: toId },
        lock: { mode: 'pessimistic_write' },
      });
      if (from.balance < amount) {
        throw new UnprocessableEntityException('insufficient funds');
      }
      from.balance -= amount;
      to.balance += amount;
      await manager.save([from, to]);
      await manager.insert(LedgerEntry, { fromId, toId, amount });
    });
  }
}

The callback runs inside one transaction: if it throws, TypeORM rolls everything back, and if it returns, it commits. Use the manager passed to the callback for every query; a repository injected elsewhere would use a different connection and escape the transaction. The pessimistic lock stops two simultaneous transfers from reading the same old balance.

The stand-in uses Node's built-in node:sqlite with explicit BEGIN, COMMIT and ROLLBACK. A CHECK constraint rejects negative balances, so the failure comes from the database itself.

Node.js Exercise 3: transaction and rollback with node:sqlite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second transfer writes its ledger row first and then fails on the CHECK constraint, yet the final ledger count did not change. That is the whole value of a transaction: the earlier statement is undone together with the failing one.

Exercise 4: a retrying queue with idempotent jobs

Task. Send a welcome email through a queue. A failing job must retry up to three times with a growing delay, and adding the same job twice must not send two emails.

Solution (Nest with BullMQ, read-only)
TypeScript
// registering and adding
BullModule.registerQueue({ name: 'mail' })

await this.mailQueue.add(
  'welcome',
  { userId },
  {
    jobId: `welcome-${userId}`,   // a job with an existing id is not added again
    attempts: 3,
    backoff: { type: 'exponential', delay: 1000 },
    removeOnComplete: true,
  },
);

// consuming
@Processor('mail')
export class MailProcessor extends WorkerHost {
  async process(job: Job<{ userId: number }>) {
    await this.mail.sendWelcome(job.data.userId); // throw to trigger a retry
  }
}

Retries mean a job can run more than once, so the work itself should also be safe to repeat (for example by checking a "welcome sent" flag). The stand-in runs a small queue with a fake clock for the backoff, so nothing really waits.

Node.js Exercise 4: queue with retries, backoff and de-duplication

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The flaky job succeeds on the third attempt after waiting 1000 ms and then 2000 ms. The broken job runs out of attempts and ends as failed, which in a real system is where you would alert someone or move it to a dead-letter list. The duplicate welcome-1 was ignored when it was added.

Exercise 5: where does it belong?

Task. For each requirement, name the Nest feature you would use. Write your answers before reading on.

  1. Read DATABASE_URL once and fail at startup when it is missing.
  2. Add a Server-Timing style header to every response.
  3. Send a receipt email after a purchase without making the customer wait.
  4. Make one AuditContext object per HTTP request, shared by every service in that request.
Solution
  1. ConfigModule with a validated schema, so a bad environment stops the app before it serves traffic (Configuration and Environment).
  2. An interceptor, because it can run code before and after the handler and see the response.
  3. A queue job (or at minimum an event listener), so the slow work happens outside the request.
  4. A request-scoped provider, remembering that every provider that depends on it also becomes request-scoped, which costs performance.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does forRootAsync exist next to forRoot?

    forRoot takes ready-made values. forRootAsync takes a factory that can inject other providers and await results before the options exist.
  2. 2. In TransfersService, why must every query use the manager passed into the transaction callback?

    Only the manager given to the callback is bound to the transaction's connection, so a rollback undoes its statements and nothing else.
  3. 3. A queue job may be retried three times. What should you make sure about the work it does?

    A retry can happen after the work partly succeeded, so repeating it must not duplicate the effect (idempotency).
  4. 4. Two interceptors are bound as @UseInterceptors(A, B). Which statement is true?

    Interceptors nest like an onion, with the first listed as the outer layer.
  5. 5. What does a jobId do in BullMQ?

    A stable id makes adding the same logical job twice harmless, which complements an idempotent processor.

Summary

  • Dynamic modules are functions returning module descriptions; use forRootAsync when options depend on other providers.
  • Interceptors wrap handlers like layers of an onion and can reshape results, measure time or turn slow calls into a 408.
  • A transaction groups changes so they all happen or none do; use the transaction's own manager for every query.
  • Queues retry failed jobs with backoff, so jobs and their work must be idempotent, and a stable job id prevents duplicates.
  • Match each requirement to the lightest feature that fits: config, interceptor, queue or scoped provider.

Next, test your recall with NestJS Interview Questions.