DEV Community

Cover image for How to build a project-management API in Node.js with NestJS: permissions, races, SSE
Kamil Mysliwiec for NestJS

Posted on Originally published at docs.nestjs.com

How to build a project-management API in Node.js with NestJS: permissions, races, SSE

If you're choosing a stack for a project-management backend (projects, tasks, comments, a board that updates itself), it looks like a CRUD app, and any Node.js framework gets you to the first endpoint in an afternoon. The hard parts show up once a team uses it. Two people drag the same card at the same moment. Someone pages through the task list while someone else adds tasks to it. A browser tab streams live updates and must only ever see its own projects. A reminder job runs on every instance of the API, and the obvious version of it sends the same reminder more than once.

In this post I'll build that API with NestJS 12, PostgreSQL and Drizzle, every file of it, and spend most of the words on those parts. The docs version, kept up to date, is Build a project-management API in Node.js.

What we're building

Here's the feature list, and what each item means once several people use the app at the same time:

  • Permissions per record, not per route. Each request is checked against the project, task or comment it touches, with policies from @nestjs/authorization. Members of a project can read everything in it. A task can be changed by whoever it's assigned to, or by a project admin. A comment can be edited by the person who wrote it, and nobody else. To a non-member, a project and everything inside it simply doesn't exist: every request answers 404.
  • Status changes that can't overwrite each other. A task goes from todo to in_progress to done through a conditional update, so when two people move one card simultaneously, only one of them succeeds.
  • A task list that pages correctly while it changes. You can filter by status, assignee and due date, the pages come from keyset pagination, and every way of reading the list has an index behind it.
  • Live updates. Members get each change in the project pushed to them over Server-Sent Events, with @nestjs/event-emitter feeding the stream.
  • Due-date reminders. A cron job reminds assignees of open tasks due within a day, and @nestjs/locks makes sure only one instance runs it.
  • Tests for the hard parts, run against PostgreSQL: the races, the stream and the reminders.

These are the routes, grouped by the part of the post where they appear:

  • Inherited from the starting point: POST /auth/sign-up, POST /auth/token, POST /auth/token/refresh, POST /auth/token/revoke, GET /me, GET /health/live, GET /health/ready.
  • Projects and their members: POST /projects, GET /projects, GET /projects/:projectId/members, POST /projects/:projectId/members.
  • Tasks: POST /projects/:projectId/tasks, GET /projects/:projectId/tasks, GET /tasks/:id, PATCH /tasks/:id, POST /tasks/:id/status.
  • Comments: GET /tasks/:taskId/comments, POST /tasks/:taskId/comments, PATCH /comments/:id.
  • The live stream: GET /projects/:projectId/events.

The starting point: a JWT API on PostgreSQL

Every API needs sign-up, access and refresh tokens, input validation, rate limits, an OpenAPI document and health checks, and none of that changes for a project-management tool. So I'm reusing the finished app from Build a REST API with JWT authentication, and I'll show its files below without walking through them again. These commands create the project and install everything at once: the JWT API's dependencies, plus @nestjs/authorization, @nestjs/event-emitter, @nestjs/schedule and @nestjs/locks, which are new here.

$ npm i -g @nestjs/cli
$ nest new projects-api --minimal
$ cd projects-api
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/authorization @nestjs/event-emitter @nestjs/schedule @nestjs/locks @nestjs/throttler @nestjs/swagger @nestjs/terminus
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite
Enter fullscreen mode Exit fullscreen mode

Add a script for the end-to-end tests to package.json:

"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
Enter fullscreen mode Exit fullscreen mode

The app gets its own PostgreSQL container:

$ docker run -d --name projects-db -e POSTGRES_PASSWORD=projects -e POSTGRES_DB=projects -p 5432:5432 postgres:17
Enter fullscreen mode Exit fullscreen mode

Put its connection string in .env, together with the key that signs access tokens:

DATABASE_URL=postgres://postgres:projects@localhost:5432/projects
# Generate with: openssl rand -base64 32
JWT_SECRET=
Enter fullscreen mode Exit fullscreen mode

Configuration and the entry point

The environment is parsed with a Zod schema at boot. If DATABASE_URL is missing or JWT_SECRET is shorter than 32 characters, the process exits before it takes a single request. CORS_ORIGINS can stay unset; with an empty list, no browser origin is allowed to call the API.

// src/config.ts
import { z } from 'zod';

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  // Signs the access tokens: at least 32 bytes.
  JWT_SECRET: z.string().min(32),
  // The browser origins allowed to call the API, comma-separated. None by default.
  CORS_ORIGINS: z
    .string()
    .default('')
    .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
    .pipe(z.array(z.url())),
});

export type Env = z.infer<typeof envSchema>;
Enter fullscreen mode Exit fullscreen mode

main.ts comes straight from the JWT API; the only edit is the OpenAPI document's title. It sets up the logger (JSON output when NODE_ENV is production, with passwords and tokens always masked), adds security headers, enables shutdown hooks and CORS, and serves Swagger UI at /docs:

// src/main.ts
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule, ObserveInstrument } from './app.module.js';
import type { Env } from './config.js';

const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  instrument: ObserveInstrument,
  logger: new ConsoleLogger({
    // One JSON object per line in production; readable text in development.
    json: production,
    // Masks these properties wherever they appear in a logged object.
    redact: ['password', 'authorization', 'accessToken', 'refreshToken'],
  }),
});
app.useSecurityHeaders();
app.enableShutdownHooks();

const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });

const document = new DocumentBuilder()
  .setTitle('Projects API')
  .setVersion('1.0')
  .addBearerAuth()
  .addSecurityRequirements('bearer')
  .build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));

await app.listen(config.get('PORT', { infer: true }));
Enter fullscreen mode Exit fullscreen mode

Users

@nestjs/authentication doesn't know or care what your users table looks like. It asks your code for a user, and here a user is just this:

// src/users/user.ts
export interface User {
  id: string;
  email: string;
  createdAt: Date;
}
Enter fullscreen mode Exit fullscreen mode

There's one new method in the repository compared to the JWT API: findByEmail(), which the projects service needs because you add people to a project by their email address. Everything the repository returns is a User, so password hashes never leave it:

// src/users/users.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { users } from '../database/schema.js';
import type { User } from './user.js';

const columns = { id: users.id, email: users.email, createdAt: users.createdAt };

/** Only `User` objects leave this class: password hashes stay inside. */
@Injectable()
export class UsersRepository {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** The new user, or `null` when the email is taken. */
  async create(email: string, passwordHash: string): Promise<User | null> {
    // One statement: two sign-ups with the same email can't both succeed.
    const [user] = await this.db
      .insert(users)
      .values({ email: normalize(email), passwordHash })
      .onConflictDoNothing({ target: users.email })
      .returning(columns);
    return user ?? null;
  }

  async findById(id: string): Promise<User | null> {
    const [user] = await this.db.select(columns).from(users).where(eq(users.id, id));
    return user ?? null;
  }

  async findByEmail(email: string): Promise<User | null> {
    const [user] = await this.db.select(columns).from(users).where(eq(users.email, normalize(email)));
    return user ?? null;
  }

  /** For password sign-in only. */
  async findCredentials(email: string): Promise<{ user: User; passwordHash: string } | null> {
    const [row] = await this.db.select().from(users).where(eq(users.email, normalize(email)));
    if (!row) {
      return null;
    }
    const { passwordHash, ...user } = row;
    return { user, passwordHash };
  }

  async updatePasswordHash(id: string, passwordHash: string): Promise<void> {
    await this.db.update(users).set({ passwordHash }).where(eq(users.id, id));
  }
}

const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();
Enter fullscreen mode Exit fullscreen mode

GET /me hands back whoever is signed in. It now carries @Can.Anyone(), and you'll see in the root module section why every controller in this app needs a decorator like that:

// src/users/me.controller.ts
import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import type { User } from './user.js';

@Can.Anyone()
@Controller('me')
export class MeController {
  @Get()
  me(@CurrentUser() user: User) {
    return user;
  }
}
Enter fullscreen mode Exit fullscreen mode

The module exports the repository, since both sign-in and member management use it:

// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { MeController } from './me.controller.js';
import { UsersRepository } from './users.repository.js';

@Module({
  controllers: [MeController],
  providers: [UsersRepository],
  exports: [UsersRepository],
})
export class UsersModule {}
Enter fullscreen mode Exit fullscreen mode

Authentication

This declaration tells the package your user type, once, so that @CurrentUser('id') only accepts keys of User:

// src/auth/auth-types.ts
import type { User } from '../users/user.js';

declare module '@nestjs/authentication' {
  interface AuthenticationTypes {
    user: User;
  }
}
Enter fullscreen mode Exit fullscreen mode

The credentials service registers users and checks passwords with PasswordHasher. With an unknown email, verify() still checks a dummy hash, so how long sign-in takes doesn't reveal which addresses have accounts:

// src/auth/credentials.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class CredentialsService {
  constructor(
    private readonly usersRepository: UsersRepository,
    private readonly passwordHasher: PasswordHasher,
  ) {}

  async register(email: string, password: string): Promise<User> {
    const user = await this.usersRepository.create(email, await this.passwordHasher.hash(password));
    if (!user) {
      throw new ConflictException('Email already registered');
    }
    return user;
  }

  /** The user, or `null` when the email or the password is wrong. */
  async verify(email: string, password: string): Promise<User | null> {
    const found = await this.usersRepository.findCredentials(email);
    // With no account, verify() checks a dummy hash, so the response
    // time doesn't reveal which emails are registered.
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    if (!valid || !found) {
      return null;
    }
    if (this.passwordHasher.needsRehash(found.passwordHash)) {
      await this.usersRepository.updatePasswordHash(found.user.id, await this.passwordHasher.hash(password));
    }
    return found.user;
  }
}
Enter fullscreen mode Exit fullscreen mode

The access-token provider resolves a token's sub to a user. Compared to the JWT API, the realm is now projects:

// src/auth/jwt-auth.provider.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
  constructor(
    private readonly usersRepository: UsersRepository,
    registry: AuthenticationRegistry,
  ) {
    // The key, issuer and audience come from the `accessToken` options.
    super({ realm: 'projects' });
    registry.registerProvider(this);
  }

  // Called once the signature, `exp`, `iss` and `aud` checked out.
  // Returning null (the user was deleted) rejects the token.
  validate({ sub }: JwtClaims) {
    return sub ? this.usersRepository.findById(sub) : null;
  }
}
Enter fullscreen mode Exit fullscreen mode

The request schemas for the four auth routes:

// src/auth/auth.schemas.ts
import { z } from 'zod';

export const signUpSchema = z.object({
  email: z.email(),
  password: z.string().min(12).max(128),
});
export type SignUpDto = z.infer<typeof signUpSchema>;

// No minimum here: a password set under an older rule still signs in.
export const signInSchema = z.object({
  email: z.email(),
  password: z.string().max(128),
});
export type SignInDto = z.infer<typeof signInSchema>;

export const refreshTokenSchema = z.object({
  refreshToken: z.string().min(1),
});
export type RefreshTokenDto = z.infer<typeof refreshTokenSchema>;
Enter fullscreen mode Exit fullscreen mode

The auth controller holds those four routes, all marked @Public(), with tighter rate limits on sign-up and sign-in:

// src/auth/auth.controller.ts
import { Body, Controller, HttpCode, Logger, Post, UnauthorizedException } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { SkipThrottle, Throttle, hours, minutes } from '@nestjs/throttler';
import {
  refreshTokenSchema,
  signInSchema,
  signUpSchema,
  type RefreshTokenDto,
  type SignInDto,
  type SignUpDto,
} from './auth.schemas.js';
import { CredentialsService } from './credentials.service.js';

@Public()
@ApiSecurity({})
@Controller('auth')
export class AuthController {
  private readonly logger = new Logger(AuthController.name);

  constructor(
    private readonly credentialsService: CredentialsService,
    private readonly tokenService: TokenService,
  ) {}

  @SkipThrottle({ account: true })
  @Throttle({ default: { limit: 10, ttl: hours(1) } })
  @Post('sign-up')
  async signUp(@Body({ schema: signUpSchema }) body: SignUpDto) {
    const user = await this.credentialsService.register(body.email, body.password);
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  @Throttle({
    default: { limit: 30, ttl: minutes(15) },
    account: { limit: 5, ttl: minutes(15) },
  })
  @Post('token')
  @HttpCode(200)
  async token(@Body({ schema: signInSchema }) body: SignInDto) {
    const user = await this.credentialsService.verify(body.email, body.password);
    if (!user) {
      this.logger.warn('Sign-in failed', { email: body.email });
      throw new UnauthorizedException('Invalid email or password');
    }
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  // An unknown, expired or reused refresh token gets a 401.
  @Post('token/refresh')
  @HttpCode(200)
  refresh(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
    return this.tokenService.refresh(body.refreshToken);
  }

  // Signs this device out. Unknown tokens get the same answer, as in RFC 7009.
  @Post('token/revoke')
  @HttpCode(204)
  async revoke(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
    await this.tokenService.revoke(body.refreshToken);
  }
}
Enter fullscreen mode Exit fullscreen mode

The account rate limit in AppModule uses this helper to read and normalize the email in the request body:

// src/auth/account-email.ts
/** The address the request body names, trimmed, lowercased and in Unicode NFC, or `''`. */
export function accountEmail(req: { body?: { email?: unknown } }): string {
  const email = req.body?.email;
  return typeof email === 'string' ? email.trim().normalize('NFC').toLowerCase() : '';
}
Enter fullscreen mode Exit fullscreen mode

Refresh tokens live in PostgreSQL, so every instance sees the same ones. Marking a token as used is a single conditional UPDATE, which means two refreshes with the same token can't both go through:

// src/auth/drizzle-refresh-token.store.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationStorage, type RefreshTokenRecord, type RefreshTokenStore } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq, isNull, lte } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { refreshTokens } from '../database/schema.js';

/** Refresh tokens in PostgreSQL, shared by every instance of the API. */
@Injectable()
export class DrizzleRefreshTokenStore implements RefreshTokenStore {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    storage: AuthenticationStorage,
  ) {
    storage.registerSource({ refreshTokens: this });
  }

  async getRefreshToken(id: string): Promise<RefreshTokenRecord | undefined> {
    const [row] = await this.db.select().from(refreshTokens).where(eq(refreshTokens.id, id));
    if (!row) {
      return undefined;
    }
    const { revoked: _, usedAt, claims, ...token } = row;
    return { ...token, usedAt: usedAt ?? undefined, claims: claims ?? undefined };
  }

  async saveRefreshToken(record: RefreshTokenRecord): Promise<void> {
    await this.db.insert(refreshTokens).values(record);
    // Families past their absolute lifetime can go.
    await this.db.delete(refreshTokens).where(lte(refreshTokens.familyExpiresAt, record.createdAt));
  }

  async markRefreshTokenUsed(id: string, at: Date): Promise<boolean> {
    // Conditional: of two refreshes with the same token, one updates the row.
    const updated = await this.db
      .update(refreshTokens)
      .set({ usedAt: at })
      .where(and(eq(refreshTokens.id, id), isNull(refreshTokens.usedAt)))
      .returning({ id: refreshTokens.id });
    return updated.length === 1;
  }

  async revokeRefreshTokenFamily(familyId: string): Promise<void> {
    await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.familyId, familyId));
  }

  async isRefreshTokenFamilyRevoked(familyId: string): Promise<boolean> {
    const revoked = await this.db
      .select({ id: refreshTokens.id })
      .from(refreshTokens)
      .where(and(eq(refreshTokens.familyId, familyId), eq(refreshTokens.revoked, true)))
      .limit(1);
    return revoked.length > 0;
  }

  async revokeUserRefreshTokens(userId: string): Promise<void> {
    await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.userId, userId));
  }
}
Enter fullscreen mode Exit fullscreen mode

And the module that ties these together:

// src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { AuthController } from './auth.controller.js';
import { CredentialsService } from './credentials.service.js';
import { DrizzleRefreshTokenStore } from './drizzle-refresh-token.store.js';
import { JwtAuth } from './jwt-auth.provider.js';

@Module({
  imports: [UsersModule],
  controllers: [AuthController],
  providers: [JwtAuth, CredentialsService, DrizzleRefreshTokenStore],
})
export class AuthModule {}
Enter fullscreen mode Exit fullscreen mode

Health checks

Readiness depends on the database answering a select 1 within a second:

// src/health/database.health.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { HealthIndicatorService } from '@nestjs/terminus';
import { sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';

@Injectable()
export class DatabaseHealthIndicator {
  constructor(
    private readonly healthIndicatorService: HealthIndicatorService,
    @InjectDrizzle() private readonly db: NodePgDatabase,
  ) {}

  isHealthy(key: string) {
    return this.healthIndicatorService
      .check(key)
      .attempt(async () => {
        await this.db.execute(sql`select 1`);
      })
      .withTimeout('1s');
  }
}
Enter fullscreen mode Exit fullscreen mode

The two probes are public and exempt from rate limiting:

// src/health/health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
import { SkipThrottle } from '@nestjs/throttler';
import { DatabaseHealthIndicator } from './database.health.js';

@Public()
@ApiSecurity({})
@SkipThrottle()
@Controller('health')
export class HealthController {
  constructor(
    private readonly health: HealthCheckService,
    private readonly database: DatabaseHealthIndicator,
  ) {}

  @Get('live')
  @HealthCheck()
  live() {
    return this.health.check([]);
  }

  @Get('ready')
  @HealthCheck()
  ready() {
    return this.health.check([() => this.database.isHealthy('database')]);
  }
}
Enter fullscreen mode Exit fullscreen mode

The health module registers both with Terminus:

// src/health/health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { DatabaseHealthIndicator } from './database.health.js';
import { HealthController } from './health.controller.js';

@Module({
  imports: [TerminusModule],
  controllers: [HealthController],
  providers: [DatabaseHealthIndicator],
})
export class HealthModule {}
Enter fullscreen mode Exit fullscreen mode

The JWT API also has a src/notes/ folder and a drizzle/ folder of migrations. Don't copy either: the migrations for this app get generated from its own schema, which comes next.

Migrations and tests

Drizzle Kit reads the schema from src/database/schema.ts and writes migrations to drizzle/:

// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'postgresql',
  schema: './src/database/schema.ts',
  out: './drizzle',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});
Enter fullscreen mode Exit fullscreen mode

Vitest supplies the environment for the end-to-end tests. DATABASE_URL is a placeholder there, because the tests replace the database provider with their own, and JWT_SECRET is a value meant for tests only:

// vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Design the schema for projects, tasks and comments

Here's the whole schema in one file. users and refresh_tokens are carried over from the JWT API, and everything else is new:

// src/database/schema.ts
import { sql } from 'drizzle-orm';
import {
  bigint,
  boolean,
  foreignKey,
  index,
  jsonb,
  pgSequence,
  pgTable,
  primaryKey,
  text,
  timestamp,
  uuid,
} from 'drizzle-orm/pg-core';

const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });
const ms = (name: string) => timestamp(name, { withTimezone: true, mode: 'date', precision: 3 });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  passwordHash: text('password_hash').notNull(),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const projects = pgTable('projects', {
  id: uuid('id').primaryKey().defaultRandom(),
  name: text('name').notNull(),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const projectMembers = pgTable(
  'project_members',
  {
    projectId: uuid('project_id')
      .notNull()
      .references(() => projects.id, { onDelete: 'cascade' }),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    role: text('role', { enum: ['admin', 'member'] }).notNull(),
  },
  (table) => [
    primaryKey({ columns: [table.projectId, table.userId] }),
    // "My projects" looks memberships up by user.
    index('project_members_user_id_idx').on(table.userId),
  ],
);

export const tasks = pgTable(
  'tasks',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    projectId: uuid('project_id')
      .notNull()
      .references(() => projects.id, { onDelete: 'cascade' }),
    title: text('title').notNull(),
    description: text('description').notNull(),
    status: text('status', { enum: ['todo', 'in_progress', 'done'] }).notNull().default('todo'),
    assigneeId: uuid('assignee_id'),
    dueAt: at('due_at'),
    remindedAt: at('reminded_at'),
    // To the millisecond, like a JavaScript Date, so a page cursor round-trips exactly.
    createdAt: ms('created_at').notNull().defaultNow(),
    updatedAt: ms('updated_at').notNull().defaultNow(),
  },
  (table) => [
    // The assignee is a member of the task's project, whatever the application does.
    foreignKey({
      name: 'tasks_assignee_is_member_fk',
      columns: [table.projectId, table.assigneeId],
      foreignColumns: [projectMembers.projectId, projectMembers.userId],
    }),
    // One index per way the list is read: all tasks, by status, by assignee.
    index('tasks_project_id_created_at_idx').on(table.projectId, table.createdAt, table.id),
    index('tasks_project_id_status_created_at_idx').on(table.projectId, table.status, table.createdAt, table.id),
    index('tasks_project_id_assignee_id_created_at_idx').on(
      table.projectId,
      table.assigneeId,
      table.createdAt,
      table.id,
    ),
    // The reminder job's scan: open tasks that haven't been reminded yet.
    index('tasks_due_at_unreminded_idx')
      .on(table.dueAt)
      .where(sql`${table.remindedAt} is null and ${table.status} <> 'done'`),
  ],
);

export const comments = pgTable(
  'comments',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    taskId: uuid('task_id')
      .notNull()
      .references(() => tasks.id, { onDelete: 'cascade' }),
    authorId: uuid('author_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    body: text('body').notNull(),
    createdAt: at('created_at').notNull().defaultNow(),
    updatedAt: at('updated_at').notNull().defaultNow(),
  },
  (table) => [index('comments_task_id_created_at_idx').on(table.taskId, table.createdAt)],
);

// What @nestjs/authentication keeps for refresh tokens, stored by their SHA-256.
export const refreshTokens = pgTable(
  'refresh_tokens',
  {
    id: text('id').primaryKey(),
    familyId: text('family_id').notNull(),
    userId: text('user_id').notNull(),
    createdAt: at('created_at').notNull(),
    expiresAt: at('expires_at').notNull(),
    familyExpiresAt: at('family_expires_at').notNull(),
    usedAt: at('used_at'),
    // A family is revoked when any of its tokens is.
    revoked: boolean('revoked').notNull().default(false),
    claims: jsonb('claims').$type<Record<string, unknown>>(),
  },
  (table) => [
    index('refresh_tokens_family_id_idx').on(table.familyId),
    index('refresh_tokens_user_id_idx').on(table.userId),
    index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
  ],
);

// What @nestjs/locks keeps, through DrizzleLockStore: one row per lock key.
export const locks = pgTable('locks', {
  key: text('key').primaryKey(),
  /** The holder's id; null once released. */
  owner: text('owner'),
  fencingToken: bigint('fencing_token', { mode: 'number' }).notNull(),
  /** On the database's clock: every instance agrees on it. */
  expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
});

/** Fencing tokens for every key: a sequence never goes back, so they only grow. */
export const locksFencingTokenSeq = pgSequence('locks_fencing_token_seq');

export type Project = typeof projects.$inferSelect;
export type Membership = typeof projectMembers.$inferSelect;
export type Task = typeof tasks.$inferSelect;
export type Comment = typeof comments.$inferSelect;
Enter fullscreen mode Exit fullscreen mode

Almost every line there exists for a reason that comes up again later:

  • Roles live on the membership. project_members has one row per project and user, keyed by both, and the row says whether that person is an admin or a member of that project. Since the role isn't on the user, Ada can be in charge of one project while she's an ordinary member somewhere else.
  • PostgreSQL won't let you assign a task to an outsider. The tasks_assignee_is_member_fk foreign key ties (project_id, assignee_id) to a row in project_members. Even buggy application code can't store a task assigned to someone who isn't in its project. When assignee_id is null, PostgreSQL skips the check, and the task simply has no assignee.
  • created_at on tasks has millisecond precision. It ends up inside the list's page cursor, and a JavaScript Date only holds milliseconds, whereas PostgreSQL stores microseconds unless told otherwise. The pagination section explains how that mismatch makes tasks disappear.
  • Three indexes for three ways of reading the list. One serves a project's whole list, one a single status, one a single assignee, and each sorts its entries in the same order the pages walk through them. The reminder job has a fourth, partial index that only contains open tasks nobody has been reminded about yet, so its size doesn't grow with the number of finished tasks.
  • The locks table and its sequence are for @nestjs/locks. The package stores its leases in your own database; these are the exact tables from Keep locks in your database.

Turn the schema into its first migration, then apply it to the database (Migrations has the details):

$ npx drizzle-kit generate --name=projects
$ npx drizzle-kit migrate
Enter fullscreen mode Exit fullscreen mode

Wire up the root module

AppModule imports everything up front, including feature modules that the next sections write:

// src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { DrizzleModule } from '@nestjs/drizzle';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { LocksModule } from '@nestjs/locks';
import { createObserveModule } from '@nestjs/observe';
import { ScheduleModule } from '@nestjs/schedule';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { ActivityModule } from './activity/activity.module.js';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { envSchema, type Env } from './config.js';
import { DrizzleLockStore } from './database/drizzle-lock.store.js';
import { HealthModule } from './health/health.module.js';
import { ProjectsModule } from './projects/projects.module.js';
import { TasksModule } from './tasks/tasks.module.js';
import { UsersModule } from './users/users.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // First, so it shuts down last and still sends what the other modules did.
    ObserveModule.forRoot({
      // Empty until `npx @nestjs/observe link` writes the key pair into .env: the SDK then sends nothing.
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'projects-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'projects-api',
          audience: 'projects-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    // After AuthenticationModule: its guard reads the user that authentication sets.
    AuthorizationModule.forRoot(),
    // `task.*` and `comment.*` listeners need wildcards.
    EventEmitterModule.forRoot({ wildcard: true }),
    ScheduleModule.forRoot(),
    LocksModule.forRoot(),
    ThrottlerModule.forRoot([
      // Per IP address, on every route.
      { name: 'default', ttl: minutes(1), limit: 100 },
      // Per email and IP address, wherever the request body names an account.
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    UsersModule,
    AuthModule,
    ProjectsModule,
    TasksModule,
    ActivityModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
    DrizzleLockStore,
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

The order and the options matter in two places:

  • AuthorizationModule has to come after AuthenticationModule. Each one installs a global guard, and the authorization guard looks at the user that the authentication guard attached to the request. The authorization guard is also deny-by-default: unless a route says who may call it, with @Can(), @Can.Anyone() or @Public(), it doesn't run at all. That's the reason MeController needed @Can.Anyone(), while the /auth and /health controllers were already covered by @Public().
  • Wildcards are on in EventEmitterModule, because the stream subscribes to task.* and comment.*. The reminder job needs ScheduleModule and LocksModule, and its lease is kept in PostgreSQL by DrizzleLockStore. All three are explained where they're used.

Per-record permissions with @nestjs/authorization

A rule like "admins only" on a route doesn't fit this app. Ada is an admin of one project and a member of another, and Bob may edit a task only if it's assigned to him. Every question is about one particular record, so the services answer it after they've loaded that record.

A project policy built on memberships

Your rights inside a project come from your membership of it, so the project policy receives the membership as the record it judges:

// src/projects/project.policy.ts
import { Policy } from '@nestjs/authorization';
import type { Membership } from '../database/schema.js';
import type { User } from '../users/user.js';

/** `membership` is the user's membership of the project, or `null` if they have none. */
@Policy()
export class ProjectPolicy {
  // Members see the project, its tasks and their comments.
  view(user: User, membership: Membership | null) {
    return membership?.userId === user.id;
  }

  // Admins add members.
  manage(user: User, membership: Membership | null) {
    return membership?.userId === user.id && membership.role === 'admin';
  }
}
Enter fullscreen mode Exit fullscreen mode

Both abilities accept a User rather than User | null, because every route that uses them requires a signed-in user. The services call them once the membership is loaded, the same pattern the authorization chapter uses to check orders record by record. Every service that works inside a project goes through MembershipsService for that:

// src/projects/memberships.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { AuthorizationService } from '@nestjs/authorization';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { projectMembers, type Membership } from '../database/schema.js';
import type { User } from '../users/user.js';
import { ProjectPolicy } from './project.policy.js';

@Injectable()
export class MembershipsService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly authorizationService: AuthorizationService,
  ) {}

  /** The user's membership of the project. A project they may not see is a 404, as if it didn't exist. */
  async access(user: User, projectId: string): Promise<Membership | null> {
    const [membership = null] = await this.db
      .select()
      .from(projectMembers)
      .where(and(eq(projectMembers.projectId, projectId), eq(projectMembers.userId, user.id)));
    await this.check(user, membership, 'Project not found');
    return membership;
  }

  /** Throws a 404 with `message` unless `membership` lets the user see its project. */
  async check(user: User, membership: Membership | null, message: string): Promise<void> {
    if (!(await this.authorizationService.can(ProjectPolicy, 'view', user, membership))) {
      throw new NotFoundException(message);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

For someone who isn't in the project, the answer is 404, exactly what they'd get for a project id that doesn't exist. A 403 would tell them it's there. Since can() returns false instead of throwing when access is denied, the service raises the 404 on its own. It's different for members who aren't allowed to do something: authorize() throws, and the authorization module maps that to a ForbiddenException. They know the project exists already, and a 403 tells them that signing in again won't change anything.

Projects and members

Creating a project takes a name. Adding a member takes an email and, optionally, a role, which defaults to member:

// src/projects/projects.schemas.ts
import { z } from 'zod';

export const createProjectSchema = z.object({
  name: z.string().trim().min(1).max(200),
});
export type CreateProjectDto = z.infer<typeof createProjectSchema>;

export const addMemberSchema = z.object({
  email: z.email(),
  role: z.enum(['admin', 'member']).default('member'),
});
export type AddMemberDto = z.infer<typeof addMemberSchema>;
Enter fullscreen mode Exit fullscreen mode

The service creates projects, lists the caller's own projects, lists a project's members, and adds members once the project policy says the caller may:

// src/projects/projects.service.ts
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { AuthorizationService } from '@nestjs/authorization';
import { InjectDrizzle } from '@nestjs/drizzle';
import { asc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { projectMembers, projects, users } from '../database/schema.js';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';
import { MembershipsService } from './memberships.service.js';
import { ProjectPolicy } from './project.policy.js';
import type { AddMemberDto, CreateProjectDto } from './projects.schemas.js';

@Injectable()
export class ProjectsService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly memberships: MembershipsService,
    private readonly authorizationService: AuthorizationService,
    private readonly usersRepository: UsersRepository,
  ) {}

  /** Creates the project with its creator as its first admin, or neither. */
  create(user: User, dto: CreateProjectDto) {
    return this.db.transaction(async (tx) => {
      const [project] = await tx.insert(projects).values(dto).returning();
      await tx.insert(projectMembers).values({ projectId: project.id, userId: user.id, role: 'admin' });
      return { ...project, role: 'admin' as const };
    });
  }

  /** The projects the user is a member of, with their role in each. */
  findMine(user: User) {
    return this.db
      .select({ id: projects.id, name: projects.name, createdAt: projects.createdAt, role: projectMembers.role })
      .from(projectMembers)
      .innerJoin(projects, eq(projects.id, projectMembers.projectId))
      .where(eq(projectMembers.userId, user.id))
      .orderBy(asc(projects.name));
  }

  async members(user: User, projectId: string) {
    await this.memberships.access(user, projectId);
    return this.db
      .select({ userId: users.id, email: users.email, role: projectMembers.role })
      .from(projectMembers)
      .innerJoin(users, eq(users.id, projectMembers.userId))
      .where(eq(projectMembers.projectId, projectId))
      .orderBy(asc(users.email));
  }

  async addMember(user: User, projectId: string, { email, role }: AddMemberDto) {
    const membership = await this.memberships.access(user, projectId);
    await this.authorizationService.authorize(ProjectPolicy, 'manage', user, membership);
    const member = await this.usersRepository.findByEmail(email);
    if (!member) {
      throw new NotFoundException('No user with this email');
    }
    const [added] = await this.db
      .insert(projectMembers)
      .values({ projectId, userId: member.id, role })
      .onConflictDoNothing()
      .returning();
    if (!added) {
      throw new ConflictException('Already a member');
    }
    return { userId: member.id, email: member.email, role: added.role };
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Creating a project also makes you its admin, atomically. Both inserts share a transaction. A project with no members at all would be invisible to everyone, with nobody able to fix it.
  • addMember() judges the caller by their own membership. access() fetches it (and turns non-members away with a 404), and then the policy decides whether that membership is an admin's.
  • Adding the same person twice gives a 409. onConflictDoNothing() on the primary key makes the second insert return nothing, so if two admins add the same user at the same time, one succeeds and the other is told the user is already a member. I left role changes out of this post deliberately, because they come with an extra invariant: a project must never end up without an admin.

The controller is marked @Can.Anyone(), since the real checks happen in the service. Leave that decorator off and the deny-by-default guard rejects every one of its routes:

// src/projects/projects.controller.ts
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import type { User } from '../users/user.js';
import { addMemberSchema, createProjectSchema, type AddMemberDto, type CreateProjectDto } from './projects.schemas.js';
import { ProjectsService } from './projects.service.js';

const projectId = { schema: z.uuid() };

// Every route checks the caller's membership in the service.
@Can.Anyone()
@Controller('projects')
export class ProjectsController {
  constructor(private readonly projectsService: ProjectsService) {}

  @Post()
  create(@CurrentUser() user: User, @Body({ schema: createProjectSchema }) dto: CreateProjectDto) {
    return this.projectsService.create(user, dto);
  }

  @Get()
  findMine(@CurrentUser() user: User) {
    return this.projectsService.findMine(user);
  }

  @Get(':projectId/members')
  members(@CurrentUser() user: User, @Param('projectId', projectId) id: string) {
    return this.projectsService.members(user, id);
  }

  @Post(':projectId/members')
  addMember(
    @CurrentUser() user: User,
    @Param('projectId', projectId) id: string,
    @Body({ schema: addMemberSchema }) dto: AddMemberDto,
  ) {
    return this.projectsService.addMember(user, id, dto);
  }
}
Enter fullscreen mode Exit fullscreen mode

The projects module registers the controller, the two services and the policy. It exports MembershipsService, which tasks, comments and the stream all depend on:

// src/projects/projects.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { MembershipsService } from './memberships.service.js';
import { ProjectPolicy } from './project.policy.js';
import { ProjectsController } from './projects.controller.js';
import { ProjectsService } from './projects.service.js';

@Module({
  imports: [UsersModule],
  controllers: [ProjectsController],
  providers: [ProjectsService, MembershipsService, ProjectPolicy],
  exports: [MembershipsService],
})
export class ProjectsModule {}
Enter fullscreen mode Exit fullscreen mode

Add tasks

All the request schemas for tasks live together in one file: creating and updating tasks, comment bodies, status moves, and the list's query string:

// src/tasks/tasks.schemas.ts
import { z } from 'zod';

const title = z.string().trim().min(1).max(200);
const description = z.string().max(10_000);
const status = z.enum(['todo', 'in_progress', 'done']);
// An instant with its offset, such as 2026-12-01T17:00:00Z.
const instant = z.iso.datetime({ offset: true }).transform((value) => new Date(value));

export const createTaskSchema = z.object({
  title,
  description: description.default(''),
  assigneeId: z.uuid().optional(),
  dueAt: instant.optional(),
});
export type CreateTaskDto = z.infer<typeof createTaskSchema>;

// `null` unassigns a task or clears its due date. Strict: a `status` here is a 400, not ignored.
export const updateTaskSchema = z
  .strictObject({ title, description, assigneeId: z.uuid().nullable(), dueAt: instant.nullable() })
  .partial();
export type UpdateTaskDto = z.infer<typeof updateTaskSchema>;

export const commentSchema = z.object({
  body: z.string().trim().min(1).max(5_000),
});
export type CommentDto = z.infer<typeof commentSchema>;

// The client says which status it moves the task from: the status it showed the user.
export const moveTaskSchema = z
  .object({ from: status, to: status })
  .refine(({ from, to }) => from !== to, { message: 'from and to must differ', path: ['to'] });
export type MoveTaskDto = z.infer<typeof moveTaskSchema>;

export interface TaskCursor {
  createdAt: string;
  id: string;
}

const cursorSchema = z.tuple([z.iso.datetime(), z.uuid()]);

/** The position after the last task of a page, opaque to the client. */
export const encodeCursor = ({ createdAt, id }: { createdAt: Date; id: string }) =>
  Buffer.from(JSON.stringify([createdAt.toISOString(), id])).toString('base64url');

const cursor = z.string().max(200).transform((value, ctx): TaskCursor => {
  let decoded: unknown;
  try {
    decoded = JSON.parse(Buffer.from(value, 'base64url').toString());
  } catch {}
  const parsed = cursorSchema.safeParse(decoded);
  if (!parsed.success) {
    ctx.addIssue({ code: 'custom', message: 'Invalid cursor' });
    return z.NEVER;
  }
  const [createdAt, id] = parsed.data;
  return { createdAt, id };
});

export const listTasksQuerySchema = z.object({
  status: status.optional(),
  assigneeId: z.uuid().optional(),
  dueBefore: instant.optional(),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  after: cursor.optional(),
});
export type ListTasksQuery = z.infer<typeof listTasksQuerySchema>;
Enter fullscreen mode Exit fullscreen mode

Some of those rules are there to close specific holes:

  • In an update, null means "clear it", but only for assigneeId and dueAt. It unassigns the task or removes the due date. Sending null for any other field, the title for example, gets a 400.
  • Unknown keys are rejected, not ignored. A regular z.object() drops keys it doesn't recognize. A PATCH carrying a status would then come back with a 200 and change nothing, which is worse than an error. With z.strictObject() it's a 400 that names the offending key. Statuses are changed through their own endpoint.
  • Timestamps must include an offset. Thanks to the offset option, z.iso.datetime() takes both 2026-12-01T17:00:00+01:00 and 2026-12-01T16:00:00Z, but turns down a plain date, since the server would have to guess its time zone.
  • The cursor is opaque. It's a base64url string that clients hand back as they got it, and the server validates it like any other parameter. If it doesn't decode to a timestamp plus an id, the request is a 400.

Who may change a task

Adding tasks and comments is open to every member. Editing a task is reserved for the person it's assigned to and for project admins. That depends on the task and on the caller's membership in the task's project, so the ability gets both:

// src/tasks/task.policy.ts
import { Policy } from '@nestjs/authorization';
import type { Membership, Task } from '../database/schema.js';
import type { User } from '../users/user.js';

@Policy()
export class TaskPolicy {
  // The assignee or a project admin changes a task. `membership` is the user's, in the task's project.
  update(user: User, task: Task, membership: Membership | null) {
    if (membership?.userId !== user.id || membership.projectId !== task.projectId) {
      return false;
    }
    return membership.role === 'admin' || task.assigneeId === user.id;
  }
}
Enter fullscreen mode Exit fullscreen mode

The tasks service fetches each task along with the caller's membership of its project in a single query, then runs the policy against what came back:

// src/tasks/tasks.service.ts
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { AuthorizationService } from '@nestjs/authorization';
import { InjectDrizzle } from '@nestjs/drizzle';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { and, desc, eq, lt, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { DatabaseError } from 'pg';
import type { ProjectActivity } from '../activity/project-activity.js';
import { projectMembers, tasks, type Task } from '../database/schema.js';
import { MembershipsService } from '../projects/memberships.service.js';
import type { User } from '../users/user.js';
import { TaskPolicy } from './task.policy.js';
import {
  encodeCursor,
  type CreateTaskDto,
  type ListTasksQuery,
  type MoveTaskDto,
  type UpdateTaskDto,
} from './tasks.schemas.js';

@Injectable()
export class TasksService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly memberships: MembershipsService,
    private readonly authorizationService: AuthorizationService,
    private readonly eventEmitter: EventEmitter2,
  ) {}

  /** Any member adds a task to the project. */
  async create(user: User, projectId: string, dto: CreateTaskDto): Promise<Task> {
    await this.memberships.access(user, projectId);
    const [task] = await this.db
      .insert(tasks)
      .values({ ...dto, projectId })
      .returning()
      .catch(assigneeNotMember);
    this.emit({ type: 'task.created', projectId, data: task });
    return task;
  }

  /** A page of the project's tasks, newest first. */
  async list(user: User, projectId: string, { status, assigneeId, dueBefore, limit, after }: ListTasksQuery) {
    await this.memberships.access(user, projectId);
    const rows = await this.db
      .select()
      .from(tasks)
      .where(
        and(
          eq(tasks.projectId, projectId),
          status ? eq(tasks.status, status) : undefined,
          assigneeId ? eq(tasks.assigneeId, assigneeId) : undefined,
          dueBefore ? lt(tasks.dueAt, dueBefore) : undefined,
          // Keyset pagination: the tasks after the cursor's, in the index's order.
          after
            ? sql`(${tasks.createdAt}, ${tasks.id}) < (${after.createdAt}::timestamptz, ${after.id}::uuid)`
            : undefined,
        ),
      )
      .orderBy(desc(tasks.createdAt), desc(tasks.id))
      .limit(limit + 1);
    const items = rows.slice(0, limit);
    return { items, nextCursor: rows.length > limit ? encodeCursor(items[items.length - 1]) : null };
  }

  async findOne(user: User, id: string): Promise<Task> {
    return (await this.load(user, id)).task;
  }

  /** The assignee or an admin changes the task's fields. */
  async update(user: User, id: string, dto: UpdateTaskDto): Promise<Task> {
    const { task, membership } = await this.load(user, id);
    await this.authorizationService.authorize(TaskPolicy, 'update', user, task, membership);
    const [updated] = await this.db
      .update(tasks)
      // A new due date gets a new reminder.
      .set({ ...dto, remindedAt: dto.dueAt === undefined ? undefined : null, updatedAt: new Date() })
      .where(eq(tasks.id, id))
      .returning()
      .catch(assigneeNotMember);
    if (!updated) {
      throw new NotFoundException('Task not found');
    }
    this.emit({ type: 'task.updated', projectId: updated.projectId, data: updated });
    return updated;
  }

  /** Moves the task from the status the client saw to another, or answers 409 if it has moved since. */
  async move(user: User, id: string, { from, to }: MoveTaskDto): Promise<Task> {
    const { task, membership } = await this.load(user, id);
    await this.authorizationService.authorize(TaskPolicy, 'update', user, task, membership);
    // Conditional: of two moves from the same status, one wins.
    const [moved] = await this.db
      .update(tasks)
      .set({ status: to, updatedAt: new Date() })
      .where(and(eq(tasks.id, id), eq(tasks.status, from)))
      .returning();
    if (!moved) {
      throw new ConflictException(`Task is no longer ${from}`);
    }
    this.emit({ type: 'task.updated', projectId: moved.projectId, data: moved });
    return moved;
  }

  /** The task with the user's membership of its project, in one query. */
  async load(user: User, id: string) {
    const [row] = await this.db
      .select({ task: tasks, membership: projectMembers })
      .from(tasks)
      .leftJoin(projectMembers, and(eq(projectMembers.projectId, tasks.projectId), eq(projectMembers.userId, user.id)))
      .where(eq(tasks.id, id));
    if (!row) {
      throw new NotFoundException('Task not found');
    }
    // A task in a project the user isn't in is as missing as one that doesn't exist.
    await this.memberships.check(user, row.membership, 'Task not found');
    return row;
  }

  private emit(activity: ProjectActivity) {
    this.eventEmitter.emit(activity.type, activity);
  }
}

/** The assignee foreign key's violation as a 400, rather than a 500. */
function assigneeNotMember(error: unknown): never {
  const cause = error instanceof Error ? error.cause : undefined;
  if (cause instanceof DatabaseError && cause.constraint === 'tasks_assignee_is_member_fk') {
    throw new BadRequestException('The assignee is not a member of this project');
  }
  throw error;
}
Enter fullscreen mode Exit fullscreen mode
  • load() costs one round trip. It reads the task left-joined to the caller's project_members row. Whether the task doesn't exist or belongs to a project you're not in, you get the same 404.
  • Events go out only after the database has accepted the write. The stream can't announce a change that the database refused. The listener on the other end is built later in the post.
  • Assigning a task to a non-member is a client error, so it's a 400. The foreign key blocks the insert or update, and assigneeNotMember() converts a violation of that particular constraint into a BadRequestException. Drizzle wraps the error from pg, so you find the constraint name on cause. Every other database failure stays a 500, which is correct.
  • Changing the due date resets reminded_at, so the assignee gets a fresh reminder for the new deadline.

Prevent lost updates when two people move the same task

Here's the scenario. Ada and Bob both have the board open. Bob drags a card from todo to in_progress while Ada, at the same instant, drags the same card from todo to done. If the UPDATE just sets the new status, both requests return success, whichever lands second overwrites the first, and one of the two is now looking at a board that's out of date with no hint that anything happened.

The fix is to make the client tell the server where it's moving the card from: the status the user saw when they dragged it. move() adds that status to the UPDATE's WHERE clause. If someone else moved the task in the meantime, nothing matches, nothing changes, and the client gets a 409, its cue to reload the task and let the user decide again.

What makes this safe is that the status is compared inside the writing statement itself, not in the read that load() did for the policy. The UPDATE locks the row, so when ten moves out of todo arrive together, exactly one of them still sees todo. The tests at the end send those ten requests at once, and I'll also show what happened when the check was moved to the earlier read.

Keyset pagination for the task list

list() serves one page of a project's tasks, newest first, with whatever filters the client passed. I'm using a cursor instead of an offset here, and there are two reasons. First, offsets drift: if a task is added while someone reads page one, everything shifts down a slot and page two starts with a task they've already seen. Second, offsets get slower the deeper you go, because PostgreSQL has to walk past every skipped row. A cursor instead points at the last task on the current page, by created_at and id, and the next page starts right after it:

(created_at, id) < ($1, $2)  -- ORDER BY created_at DESC, id DESC
Enter fullscreen mode Exit fullscreen mode

Why the id? Because created_at isn't unique: every row inserted by the same statement gets the same value. And why does precision matter? Because the timestamp in the cursor must match the stored one exactly. At PostgreSQL's default microsecond precision, a task created at 21:54:53.387412 turns into a cursor of 21:54:53.387, and any task from that same millisecond that sorts after it is never shown on any page. That's why the column keeps milliseconds only.

Since the WHERE and the ORDER BY line up with an index, PostgreSQL reads only one page worth of index entries, no matter how far into the list you are, and the cursor comparison is part of the index condition. The plans were checked with EXPLAIN on 100,000 tasks spread over 50 projects, and each kind of list scans its own index backward: a board's todo column uses tasks_project_id_status_created_at_idx, one person's tasks use tasks_project_id_assignee_id_created_at_idx, and a later page of the full list uses tasks_project_id_created_at_idx. The reminder query goes through tasks_due_at_unreminded_idx.

dueBefore doesn't get an index of its own; it filters the rows the chosen index returns. It's a filter that narrows a list, and sorting by due date would mean a cursor over a nullable column. If you do want a list ordered by due date, use the same technique with (due_at, id), plus an index that matches it.

The controller exposes the five task routes:

// src/tasks/tasks.controller.ts
import { Body, Controller, Get, HttpCode, Param, Patch, Post, Query } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import type { User } from '../users/user.js';
import {
  createTaskSchema,
  listTasksQuerySchema,
  moveTaskSchema,
  updateTaskSchema,
  type CreateTaskDto,
  type ListTasksQuery,
  type MoveTaskDto,
  type UpdateTaskDto,
} from './tasks.schemas.js';
import { TasksService } from './tasks.service.js';

const uuid = { schema: z.uuid() };

// Every route checks the caller's permissions in the service, against the task.
@Can.Anyone()
@Controller()
export class TasksController {
  constructor(private readonly tasksService: TasksService) {}

  @Post('projects/:projectId/tasks')
  create(
    @CurrentUser() user: User,
    @Param('projectId', uuid) projectId: string,
    @Body({ schema: createTaskSchema }) dto: CreateTaskDto,
  ) {
    return this.tasksService.create(user, projectId, dto);
  }

  @Get('projects/:projectId/tasks')
  list(
    @CurrentUser() user: User,
    @Param('projectId', uuid) projectId: string,
    @Query({ schema: listTasksQuerySchema }) query: ListTasksQuery,
  ) {
    return this.tasksService.list(user, projectId, query);
  }

  @Get('tasks/:id')
  findOne(@CurrentUser() user: User, @Param('id', uuid) id: string) {
    return this.tasksService.findOne(user, id);
  }

  @Patch('tasks/:id')
  update(@CurrentUser() user: User, @Param('id', uuid) id: string, @Body({ schema: updateTaskSchema }) dto: UpdateTaskDto) {
    return this.tasksService.update(user, id, dto);
  }

  @Post('tasks/:id/status')
  @HttpCode(200)
  move(@CurrentUser() user: User, @Param('id', uuid) id: string, @Body({ schema: moveTaskSchema }) dto: MoveTaskDto) {
    return this.tasksService.move(user, id, dto);
  }
}
Enter fullscreen mode Exit fullscreen mode

A POST route in Nest answers 201 unless you say otherwise. POST /tasks/:id/status doesn't create anything, it changes a task that already exists, so it's set to 200.

Comment on tasks

A comment can only be edited by its author, and the comment itself carries everything needed to decide that. So this ability needs nothing but the comment:

// src/tasks/comment.policy.ts
import { Policy } from '@nestjs/authorization';
import type { Comment } from '../database/schema.js';
import type { User } from '../users/user.js';

@Policy()
export class CommentPolicy {
  // Only its author edits a comment: an admin can't edit someone else's either.
  edit(user: User, comment: Comment) {
    return comment.authorId === user.id;
  }
}
Enter fullscreen mode Exit fullscreen mode

commentSchema, the body schema, is already in tasks.schemas.ts. The comments service lists, creates and edits comments, and leans on TasksService.load() for the membership check:

// src/tasks/comments.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { AuthorizationService } from '@nestjs/authorization';
import { InjectDrizzle } from '@nestjs/drizzle';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { and, asc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type { ProjectActivity } from '../activity/project-activity.js';
import { comments, projectMembers, tasks, type Comment } from '../database/schema.js';
import { MembershipsService } from '../projects/memberships.service.js';
import type { User } from '../users/user.js';
import { CommentPolicy } from './comment.policy.js';
import type { CommentDto } from './tasks.schemas.js';
import { TasksService } from './tasks.service.js';

@Injectable()
export class CommentsService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly tasksService: TasksService,
    private readonly memberships: MembershipsService,
    private readonly authorizationService: AuthorizationService,
    private readonly eventEmitter: EventEmitter2,
  ) {}

  /** The task's comments, oldest first, for members of its project. */
  async list(user: User, taskId: string): Promise<Comment[]> {
    await this.tasksService.load(user, taskId);
    return this.db.select().from(comments).where(eq(comments.taskId, taskId)).orderBy(asc(comments.createdAt)).limit(200);
  }

  /** Any member comments on a task. */
  async create(user: User, taskId: string, { body }: CommentDto): Promise<Comment> {
    const { task } = await this.tasksService.load(user, taskId);
    const [comment] = await this.db.insert(comments).values({ taskId, authorId: user.id, body }).returning();
    this.emit({ type: 'comment.created', projectId: task.projectId, data: comment });
    return comment;
  }

  /** Only the author edits a comment. */
  async update(user: User, id: string, { body }: CommentDto): Promise<Comment> {
    const [row] = await this.db
      .select({ comment: comments, projectId: tasks.projectId, membership: projectMembers })
      .from(comments)
      .innerJoin(tasks, eq(tasks.id, comments.taskId))
      .leftJoin(projectMembers, and(eq(projectMembers.projectId, tasks.projectId), eq(projectMembers.userId, user.id)))
      .where(eq(comments.id, id));
    if (!row) {
      throw new NotFoundException('Comment not found');
    }
    await this.memberships.check(user, row.membership, 'Comment not found');
    await this.authorizationService.authorize(CommentPolicy, 'edit', user, row.comment);
    const [updated] = await this.db
      .update(comments)
      .set({ body, updatedAt: new Date() })
      .where(and(eq(comments.id, id), eq(comments.authorId, user.id)))
      .returning();
    if (!updated) {
      throw new NotFoundException('Comment not found');
    }
    this.emit({ type: 'comment.updated', projectId: row.projectId, data: updated });
    return updated;
  }

  private emit(activity: ProjectActivity) {
    this.eventEmitter.emit(activity.type, activity);
  }
}
Enter fullscreen mode Exit fullscreen mode

In update(), the order of the checks picks the status code. A non-member gets a 404, consistent with every other record inside a project; a member who didn't write the comment gets a 403. On top of that, the UPDATE itself filters on the author, so whatever went wrong earlier, the statement can never touch a comment written by someone else.

The comments controller adds the three comment routes:

// src/tasks/comments.controller.ts
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import type { User } from '../users/user.js';
import { commentSchema, type CommentDto } from './tasks.schemas.js';
import { CommentsService } from './comments.service.js';

const uuid = { schema: z.uuid() };

@Can.Anyone()
@Controller()
export class CommentsController {
  constructor(private readonly commentsService: CommentsService) {}

  @Get('tasks/:taskId/comments')
  list(@CurrentUser() user: User, @Param('taskId', uuid) taskId: string) {
    return this.commentsService.list(user, taskId);
  }

  @Post('tasks/:taskId/comments')
  create(@CurrentUser() user: User, @Param('taskId', uuid) taskId: string, @Body({ schema: commentSchema }) dto: CommentDto) {
    return this.commentsService.create(user, taskId, dto);
  }

  @Patch('comments/:id')
  update(@CurrentUser() user: User, @Param('id', uuid) id: string, @Body({ schema: commentSchema }) dto: CommentDto) {
    return this.commentsService.update(user, id, dto);
  }
}
Enter fullscreen mode Exit fullscreen mode

TasksModule puts tasks and comments together, with their policies and the reminder job that comes later:

// src/tasks/tasks.module.ts
import { Module } from '@nestjs/common';
import { ProjectsModule } from '../projects/projects.module.js';
import { CommentPolicy } from './comment.policy.js';
import { CommentsController } from './comments.controller.js';
import { CommentsService } from './comments.service.js';
import { RemindersJob } from './reminders.job.js';
import { TaskPolicy } from './task.policy.js';
import { TasksController } from './tasks.controller.js';
import { TasksService } from './tasks.service.js';

@Module({
  imports: [ProjectsModule],
  controllers: [TasksController, CommentsController],
  providers: [TasksService, CommentsService, TaskPolicy, CommentPolicy, RemindersJob],
})
export class TasksModule {}
Enter fullscreen mode Exit fullscreen mode

Stream changes with Server-Sent Events

Without live updates, you only see what your teammates changed when you refresh the page. Server-Sent Events solve that over ordinary HTTP. The browser opens a request and leaves it open, and the server writes an event into that response whenever something changes. Our services already emit an event through EventEmitter2 after each change, so the stream just needs to subscribe.

Each event names the change, the project it happened in, and the record exactly as the database returned it:

// src/activity/project-activity.ts
import type { Comment, Task } from '../database/schema.js';

/** Something that changed in a project, emitted after the change was written. */
export type ProjectActivity =
  | { type: 'task.created' | 'task.updated'; projectId: string; data: Task }
  | { type: 'comment.created' | 'comment.updated'; projectId: string; data: Comment };
Enter fullscreen mode Exit fullscreen mode

The activity service picks those events up and hands every project's stream only the events of that project:

// src/activity/activity.service.ts
import { Injectable, type MessageEvent } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { filter, interval, map, merge, of, Subject, type Observable } from 'rxjs';
import type { ProjectActivity } from './project-activity.js';

@Injectable()
export class ActivityService {
  // One listener for the whole application; each stream filters it.
  private readonly activity$ = new Subject<ProjectActivity>();

  @OnEvent('task.*')
  onTask(activity: ProjectActivity) {
    this.activity$.next(activity);
  }

  @OnEvent('comment.*')
  onComment(activity: ProjectActivity) {
    this.activity$.next(activity);
  }

  /** The project's activity as server-sent events. */
  stream(projectId: string): Observable<MessageEvent> {
    return merge(
      // Tells the client the stream is open: changes from here on reach it.
      of({ comment: 'connected' }),
      this.activity$.pipe(
        filter((activity) => activity.projectId === projectId),
        map(({ type, data }) => ({ type, data })),
      ),
      // Proxies close connections that stay silent; a comment every 20 seconds keeps it open.
      interval(20_000).pipe(map(() => ({ comment: 'keep-alive' }))),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • The app has exactly one listener per event family. @OnEvent() registers onTask() and onComment() once, when the app boots, and both forward whatever they receive into a Subject. Each open stream subscribes to that subject and filters for its project. If you registered a fresh emitter listener for every connection instead, the eleventh open tab would exceed EventEmitter2's default maxListeners of ten, and you'd get a memory-leak warning.
  • The event name is the type, so frontend code subscribes with addEventListener('task.updated', ...), and the data arrives serialized as JSON (see Usage).
  • The stream opens with a comment line, : connected. That's the signal, for a client and for the test at the end, that the subscription is live and every change from now on will arrive. EventSource skips comment lines.
  • Every 20 seconds, a keep-alive comment goes out, so proxies don't close the connection for being idle. Once the client disconnects, Nest unsubscribes from the Observable, and that tears down the interval along with the subscription to the Subject (see Client disconnection).

Check membership before the stream starts

Only members of a project should be able to open its stream. The natural place for the check would be the handler, like everywhere else, but that's a trap. An @Sse() route writes its response headers the moment the handler is invoked. If an async handler then throws a NotFoundException, the client has already received a 200, and the stream it got contains one event: event: error, with data: Project not found. That's the behavior on @nestjs/core 12.5.1 with the Node adapter. A guard runs before the handler is called, so an exception thrown there becomes a proper 404:

// src/activity/project-member.guard.ts
import { Injectable, NotFoundException, type CanActivate, type ExecutionContext } from '@nestjs/common';
import { z } from 'zod';
import { MembershipsService } from '../projects/memberships.service.js';
import type { User } from '../users/user.js';

/**
 * Checks that the user is a member of the route's project before the handler runs.
 * An `@Sse()` route sends its headers before an async handler settles, so a 404
 * thrown there would reach the client as an `error` event on a 200 stream.
 */
@Injectable()
export class ProjectMemberGuard implements CanActivate {
  constructor(private readonly memberships: MembershipsService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const { user, params } = context.switchToHttp().getRequest<{ user: User; params: { projectId: string } }>();
    // Guards run before pipes, so the id isn't validated yet.
    if (!z.uuid().safeParse(params.projectId).success) {
      throw new NotFoundException('Project not found');
    }
    await this.memberships.access(user, params.projectId);
    return true;
  }
}
Enter fullscreen mode Exit fullscreen mode

The controller applies the guard to the stream route:

// src/activity/activity.controller.ts
import { Controller, Param, Sse, UseGuards, type MessageEvent } from '@nestjs/common';
import { Can } from '@nestjs/authorization';
import type { Observable } from 'rxjs';
import { ActivityService } from './activity.service.js';
import { ProjectMemberGuard } from './project-member.guard.js';

@Can.Anyone()
@UseGuards(ProjectMemberGuard)
@Controller('projects/:projectId/events')
export class ActivityController {
  constructor(private readonly activityService: ActivityService) {}

  // Only members get here: ProjectMemberGuard checked the project before the stream started.
  @Sse()
  stream(@Param('projectId') projectId: string): Observable<MessageEvent> {
    return this.activityService.stream(projectId);
  }
}
Enter fullscreen mode Exit fullscreen mode

The activity module pulls in the projects module, because the guard needs MembershipsService:

// src/activity/activity.module.ts
import { Module } from '@nestjs/common';
import { ProjectsModule } from '../projects/projects.module.js';
import { ActivityController } from './activity.controller.js';
import { ActivityService } from './activity.service.js';

@Module({
  imports: [ProjectsModule],
  controllers: [ActivityController],
  providers: [ActivityService],
})
export class ActivityModule {}
Enter fullscreen mode Exit fullscreen mode

By the time ProjectMemberGuard runs, the global guards have already authenticated the user. It calls the same MembershipsService.access() as everything else, so the stream answers a non-member the same way the rest of the API does. All that's left for the handler is to return the Observable.

A heads-up for the frontend: the browser's EventSource has no way to set an Authorization header, and that header is where this API expects the access token. In the browser, use fetch() instead: it sends the header and gives you the response body as a stream. The test at the end reads the stream exactly that way, in Node; a library that wraps fetch() works too.

Due-date reminders that run on one instance

Every minute, a job finds open tasks due within the next day and reminds whoever is assigned to them. @nestjs/schedule triggers it, and as soon as you run two or more instances of the API, it triggers it on each of them. That's what @OnOneInstance() from @nestjs/locks is for: the instances coordinate through a lock store they all share. The package specifies what the store must do, and your application provides it.

I'm using the Drizzle store from Keep locks in your database, which works on the locks table and sequence in our schema. One change from the chapter's version: the chapter's app defines its own Database type, so here db is typed as NodePgDatabase from drizzle-orm/node-postgres instead:

// src/database/drizzle-lock.store.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { LocksStorage, type LockAcquireResult, type LockStore } from '@nestjs/locks';
import { and, eq, gt, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { locks } from './schema.js';

/** `ttl` from now, on the database's clock. */
const expiresIn = (ttl: number) => sql`clock_timestamp() + ${ttl} * interval '1 millisecond'`;

/** The lock on `key`, if `owner` still holds it: the compare-and-set of renew() and release(). */
const heldBy = (key: string, owner: string) =>
  and(eq(locks.key, key), eq(locks.owner, owner), gt(locks.expiresAt, sql`clock_timestamp()`));

@Injectable()
export class DrizzleLockStore implements LockStore {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    storage: LocksStorage,
  ) {
    storage.registerSource(this);
  }

  async acquire(key: string, owner: string, ttl: number): Promise<LockAcquireResult> {
    // One statement: insert the lock, or take over a released or expired one. Of any number
    // of concurrent callers, one inserts or updates the row; the others find it held.
    const [row] = await this.db
      .insert(locks)
      .values({ key, owner, fencingToken: sql`nextval('locks_fencing_token_seq')`, expiresAt: expiresIn(ttl) })
      .onConflictDoUpdate({
        target: locks.key,
        // nextval() here runs after the row is locked: a later holder always gets a
        // greater token than the one before it. The row's own token is the floor, so a
        // sequence that went back (a restore, a failover) can't hand a key an old token.
        set: {
          owner,
          fencingToken: sql`greatest(nextval('locks_fencing_token_seq'), ${locks.fencingToken} + 1)`,
          expiresAt: expiresIn(ttl),
        },
        setWhere: sql`${locks.owner} is null or ${locks.expiresAt} <= clock_timestamp()`,
      })
      .returning({ fencingToken: locks.fencingToken });
    return row ? { acquired: true, fencingToken: row.fencingToken } : { acquired: false };
  }

  async renew(key: string, owner: string, ttl: number): Promise<boolean> {
    const rows = await this.db
      .update(locks)
      .set({ expiresAt: expiresIn(ttl) })
      .where(heldBy(key, owner))
      .returning({ key: locks.key });
    return rows.length === 1;
  }

  async release(key: string, owner: string): Promise<boolean> {
    // Keep the row, so the next acquire() always takes the update path above, whose token is
    // drawn after the row is locked.
    const rows = await this.db
      .update(locks)
      .set({ owner: null })
      .where(heldBy(key, owner))
      .returning({ key: locks.key });
    return rows.length === 1;
  }
}
Enter fullscreen mode Exit fullscreen mode

acquire(), renew() and release() are each a single conditional statement, so however many instances compete for the same lock, only one wins; the chapter goes through them one by one. The constructor registers the store with the locks module, and AppModule already lists it as a provider. When the app starts, the locks module logs which store it picked:

LOG [LocksModule] LocksStorage: DrizzleLockStore
Enter fullscreen mode Exit fullscreen mode

And here's the job:

// src/tasks/reminders.job.ts
import { Injectable, Logger } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { OnOneInstance } from '@nestjs/locks';
import { Cron, CronExpression } from '@nestjs/schedule';
import { and, eq, isNull, lte, ne, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { tasks, users } from '../database/schema.js';

@Injectable()
export class RemindersJob {
  private readonly logger = new Logger(RemindersJob.name);

  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** Reminds assignees of open tasks due within a day, once per task. Returns how many it sent. */
  @Cron(CronExpression.EVERY_MINUTE, { name: 'task-reminders' })
  @OnOneInstance({ key: 'tasks:due-reminders' })
  async sendReminders(): Promise<number> {
    // Claims the tasks in the statement that finds them: of two runs at once, each task goes to one.
    const due = await this.db
      .update(tasks)
      .set({ remindedAt: new Date() })
      .from(users)
      .where(
        and(
          eq(users.id, tasks.assigneeId),
          isNull(tasks.remindedAt),
          ne(tasks.status, 'done'),
          lte(tasks.dueAt, sql`now() + interval '1 day'`),
        ),
      )
      .returning({ id: tasks.id, title: tasks.title, dueAt: tasks.dueAt, email: users.email });
    for (const task of due) {
      // Send the email here, for example with @nestjs/mail.
      this.logger.log(`Reminder to ${task.email}: "${task.title}" is due ${task.dueAt?.toISOString()}`);
    }
    return due.length;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Finding the due tasks and claiming them is one statement. The UPDATE ... SET reminded_at = now() WHERE reminded_at IS NULL ... RETURNING picks the tasks and marks them as reminded at the same time, so when two runs overlap, every task goes to one of them only. Split it into a SELECT and then an UPDATE, and both runs get the same tasks. The tests at the end check exactly this, and with the split version, three overlapping runs reminded the same task three times.
  • @OnOneInstance() keeps the work on a single instance. Whichever instance fires the job first takes the lease, and the rest skip their ticks. If that instance goes away, another one picks the job up on its next tick (see Run each job on one instance). Duplicates are already ruled out by the claim; the lease is what spares the other instances from doing the scan, and it keeps every run, and every log line, on one machine.
  • The claim happens before the send. So when sending fails, that reminder is dropped, not duplicated. For real emails, use @nestjs/mail and send them from a queue with retries.
  • A skipped tick costs nothing. Each run takes everything that's due, not just what became due in the last minute, so if one tick never happened, the next one covers it.

Try it

Start the app:

$ npm run start:dev
Enter fullscreen mode Exit fullscreen mode

Create three accounts, Ada, Bob and Eve, the same way as in the JWT API, and save each one's access token in a shell variable. In these outputs, tokens and long bodies are cut short:

$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"...","expiresIn":900}
$ ADA="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ BOB="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ EVE="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
Enter fullscreen mode Exit fullscreen mode

Ada creates a project and becomes its admin. Eve is an outsider, so the project's tasks are a 404 to her. Ada then adds Bob, who can list the members now, but isn't allowed to add anyone:

$ curl localhost:3000/projects -H "$ADA" --json '{"name":"Website relaunch"}'
{"id":"b1dddeba-0a00-4997-9ed4-eec8e255e2fa","name":"Website relaunch","createdAt":"2026-11-19T22:15:10.624Z","role":"admin"}
$ PROJECT=b1dddeba-0a00-4997-9ed4-eec8e255e2fa
$ curl -i localhost:3000/projects/$PROJECT/tasks -H "$EVE"
HTTP/1.1 404 Not Found
{"message":"Project not found","error":"Not Found","statusCode":404}
$ curl localhost:3000/projects/$PROJECT/members -H "$ADA" --json '{"email":"bob@example.com"}'
{"userId":"c1ffc2db-5cf3-4835-b05a-1e0daf80903b","email":"bob@example.com","role":"member"}
$ curl -i localhost:3000/projects/$PROJECT/members -H "$BOB" --json '{"email":"eve@example.com"}'
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}
$ curl localhost:3000/projects/$PROJECT/members -H "$BOB"
[{"userId":"8290d579-c516-4f78-9688-7bae25ba082c","email":"ada@example.com","role":"admin"},{"userId":"c1ffc2db-5cf3-4835-b05a-1e0daf80903b","email":"bob@example.com","role":"member"}]
Enter fullscreen mode Exit fullscreen mode

Ada tries to assign a task to Eve and is refused, because Eve isn't a member. She gives it to Bob instead, with a due date that includes an offset, and Bob creates a second task himself:

$ curl localhost:3000/projects/$PROJECT/tasks -H "$ADA" --json '{"title":"Write the launch post","assigneeId":"8e73d73c-58e6-419a-a717-c77d845a6b9c"}'
{"message":"The assignee is not a member of this project","error":"Bad Request","statusCode":400}
$ curl localhost:3000/projects/$PROJECT/tasks -H "$ADA" --json '{"title":"Write the launch post","assigneeId":"c1ffc2db-5cf3-4835-b05a-1e0daf80903b","dueAt":"2026-12-01T17:00:00+01:00"}'
{"id":"b9690f26-f034-4985-b635-2bd112d5b132","projectId":"b1dddeba-...","title":"Write the launch post","description":"","status":"todo","assigneeId":"c1ffc2db-...","dueAt":"2026-12-01T16:00:00.000Z","remindedAt":null,"createdAt":"2026-11-19T22:15:10.951Z","updatedAt":"2026-11-19T22:15:10.951Z"}
$ curl localhost:3000/projects/$PROJECT/tasks -H "$BOB" --json '{"title":"Fix the footer links"}'
{"id":"a77318f3-3f27-4bb0-bc4b-fe8c0c12057b",...,"title":"Fix the footer links","description":"","status":"todo","assigneeId":null,...}
Enter fullscreen mode Exit fullscreen mode

Bob can't rename the second task, even though he created it: it has no assignee and he isn't an admin. Trying to set status through PATCH fails too:

$ curl -i -X PATCH localhost:3000/tasks/a77318f3-3f27-4bb0-bc4b-fe8c0c12057b -H "$BOB" --json '{"title":"Fix footer links"}'
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}
$ curl -X PATCH localhost:3000/tasks/b9690f26-f034-4985-b635-2bd112d5b132 -H "$BOB" --json '{"status":"done"}'
{"message":["Unrecognized key: \"status\""],"error":"Bad Request","statusCode":400}
Enter fullscreen mode Exit fullscreen mode

Bob moves his task to in_progress. Ada, whose board still has it in todo, tries to move it from todo to done, and gets a conflict instead:

$ curl -X POST localhost:3000/tasks/b9690f26-f034-4985-b635-2bd112d5b132/status -H "$BOB" --json '{"from":"todo","to":"in_progress"}'
{"id":"b9690f26-f034-4985-b635-2bd112d5b132",...,"status":"in_progress",...,"updatedAt":"2026-11-19T22:15:11.149Z"}
$ curl -X POST localhost:3000/tasks/b9690f26-f034-4985-b635-2bd112d5b132/status -H "$ADA" --json '{"from":"todo","to":"done"}'
{"message":"Task is no longer todo","error":"Conflict","statusCode":409}
Enter fullscreen mode Exit fullscreen mode

Now the list: first with filters, then one task at a time with the cursor, and finally with two invalid parameters in one request:

$ curl "localhost:3000/projects/$PROJECT/tasks?status=in_progress&assigneeId=c1ffc2db-5cf3-4835-b05a-1e0daf80903b" -H "$ADA"
{"items":[{"id":"b9690f26-f034-4985-b635-2bd112d5b132",...,"title":"Write the launch post",...,"status":"in_progress",...}],"nextCursor":null}
$ curl "localhost:3000/projects/$PROJECT/tasks?limit=1" -H "$ADA"
{"items":[{"id":"a77318f3-3f27-4bb0-bc4b-fe8c0c12057b",...,"title":"Fix the footer links",...}],"nextCursor":"WyIyMDI2LTExLTE5VDIyOjE1OjExLjAzOVoiLCJhNzczMThmMy0zZjI3LTRiYjAtYmM0Yi1mZThjMGMxMjA1N2IiXQ"}
$ curl "localhost:3000/projects/$PROJECT/tasks?limit=1&after=WyIyMDI2LTExLTE5VDIyOjE1OjExLjAzOVoiLCJhNzczMThmMy0zZjI3LTRiYjAtYmM0Yi1mZThjMGMxMjA1N2IiXQ" -H "$ADA"
{"items":[{"id":"b9690f26-f034-4985-b635-2bd112d5b132",...,"title":"Write the launch post",...}],"nextCursor":null}
$ curl "localhost:3000/projects/$PROJECT/tasks?dueBefore=2026-12-24&after=abc" -H "$ADA"
{"message":["dueBefore: Invalid ISO datetime","after: Invalid cursor"],"error":"Bad Request","statusCode":400}
Enter fullscreen mode Exit fullscreen mode

Bob leaves a comment. Ada, an admin, still can't rewrite it:

$ curl localhost:3000/tasks/b9690f26-f034-4985-b635-2bd112d5b132/comments -H "$BOB" --json '{"body":"First draft is in the doc."}'
{"id":"022d3d18-54e4-41ec-936e-8ab377731af8","taskId":"b9690f26-...","authorId":"c1ffc2db-...","body":"First draft is in the doc.","createdAt":"2026-11-19T22:15:11.352Z","updatedAt":"2026-11-19T22:15:11.352Z"}
$ curl -X PATCH localhost:3000/comments/022d3d18-54e4-41ec-936e-8ab377731af8 -H "$ADA" --json '{"body":"Rewritten"}'
{"message":"Forbidden","statusCode":403}
Enter fullscreen mode Exit fullscreen mode

Eve gets a regular 404 from the stream endpoint, and a request with no token gets a 401, before any streaming begins. Ada opens the stream (-N stops curl from buffering), and from a second terminal Bob finishes his task and adds a comment:

$ curl -i localhost:3000/projects/$PROJECT/events -H "$EVE"
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{"message":"Project not found","error":"Not Found","statusCode":404}
$ curl -N localhost:3000/projects/$PROJECT/events -H "$ADA"
: connected

event: task.updated
id: 1
data: {"id":"b9690f26-f034-4985-b635-2bd112d5b132",...,"status":"done",...,"updatedAt":"2026-11-19T22:15:12.507Z"}

event: comment.created
id: 2
data: {"id":"8970ada9-2ce4-4a7f-9144-e12069fbd9a0","taskId":"b9690f26-...","authorId":"c1ffc2db-...","body":"Published.",...}
Enter fullscreen mode Exit fullscreen mode

Members can read a task's comments, oldest first; Eve gets a 404:

$ curl localhost:3000/tasks/b9690f26-f034-4985-b635-2bd112d5b132/comments -H "$BOB"
[{"id":"022d3d18-54e4-41ec-936e-8ab377731af8",...,"body":"First draft is in the doc.",...},{"id":"8970ada9-2ce4-4a7f-9144-e12069fbd9a0",...,"body":"Published.",...}]
$ curl -i localhost:3000/tasks/b9690f26-f034-4985-b635-2bd112d5b132/comments -H "$EVE"
HTTP/1.1 404 Not Found
{"message":"Task not found","error":"Not Found","statusCode":404}
Enter fullscreen mode Exit fullscreen mode

Finally, a task that's due within the day. On the first tick after startup, the instance takes the lease for the job, and on the first tick after this task exists, Bob gets exactly one reminder:

$ curl localhost:3000/projects/$PROJECT/tasks -H "$ADA" --json '{"title":"Send the newsletter","assigneeId":"c1ffc2db-5cf3-4835-b05a-1e0daf80903b","dueAt":"2026-11-20T01:00:00Z"}'
{"id":"e0b29e6d-cc14-4251-a64e-61fbe530e072",...,"title":"Send the newsletter",...,"dueAt":"2026-11-20T01:00:00.000Z","remindedAt":null,...}
Enter fullscreen mode Exit fullscreen mode

In the log, you see the lease being acquired and then the reminder:

LOG [Locks] RemindersJob.sendReminders runs on this instance (lease "tasks:due-reminders:owner", fencing token 1)
LOG [RemindersJob] Reminder to bob@example.com: "Send the newsletter" is due 2026-11-20T01:00:00.000Z
Enter fullscreen mode Exit fullscreen mode

Test the races against PostgreSQL

What this API promises is mostly about concurrency, and PGlite or any other in-process database runs on a single connection, where two requests can never really race. That's why these tests use a real PostgreSQL server, with a pool of 20 connections. The stream test needs an actual HTTP response, so the app listens on a random free port, while all the other tests go through app.inject():

// test/projects.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { SchedulerRegistry } from '@nestjs/schedule';
import { Test } from '@nestjs/testing';
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { onTestFinished } from 'vitest';
import { AppModule } from '../src/app.module.js';
import { tasks } from '../src/database/schema.js';
import { RemindersJob } from '../src/tasks/reminders.job.js';

// A real PostgreSQL with a pool, so concurrent requests really race.
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('Project management API (e2e)', () => {
  const db = drizzle({ client: new Pool({ connectionString: url, max: 20 }) });
  let app: NestNodeApplication;

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    await db.execute(sql`TRUNCATE users, projects, refresh_tokens, locks CASCADE`);
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db)
      // scrypt at the default cost takes 128 MiB and a few hundred ms per hash.
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    // The stream test reads a real response, so the application listens.
    await app.listen(0, '127.0.0.1');
    // The test runs the reminder job itself.
    app.get(SchedulerRegistry).getCronJob('task-reminders').stop();
  });

  afterAll(() => app.close()); // closes the pool too

  let clients = 0;

  /** Signs a user up. Each user has an address of their own: requests are rate-limited per IP address. */
  async function signUp(name: string) {
    const remoteAddress = `10.0.0.${++clients}`;
    const payload = { email: `${name}@example.com`, password: 'correct horse battery' };
    const res = await app.inject({ method: 'POST', url: '/auth/sign-up', payload, remoteAddress });
    const headers = { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
    const me = await app.inject({ method: 'GET', url: '/me', headers, remoteAddress });
    return { id: me.json<{ id: string }>().id, headers, remoteAddress };
  }
  type Client = Awaited<ReturnType<typeof signUp>>;

  const call = ({ headers, remoteAddress }: Client, method: 'GET' | 'POST' | 'PATCH', url: string, payload?: object) =>
    app.inject({ method, url, headers, remoteAddress, payload });

  /** A project of `admin`'s, with `members` added. */
  async function createProject(admin: Client, ...members: string[]) {
    const { id } = (await call(admin, 'POST', '/projects', { name: 'Website relaunch' })).json<{ id: string }>();
    for (const name of members) {
      await call(admin, 'POST', `/projects/${id}/members`, { email: `${name}@example.com` });
    }
    return id;
  }

  async function createTask(client: Client, projectId: string, payload: object = {}) {
    const res = await call(client, 'POST', `/projects/${projectId}/tasks`, { title: 'Write the launch post', ...payload });
    return res.json<{ id: string }>().id;
  }

  let ada: Client, bob: Client, carol: Client, eve: Client;
  beforeAll(async () => {
    [ada, bob, carol, eve] = await Promise.all(['ada', 'bob', 'carol', 'eve'].map(signUp));
  });

  it('checks every request against the project, the task or the comment', async () => {
    const projectId = await createProject(ada, 'bob', 'carol');
    const taskId = await createTask(ada, projectId, { assigneeId: bob.id });
    const rename = (client: Client) => call(client, 'PATCH', `/tasks/${taskId}`, { title: 'Write the launch post, v2' });

    expect((await call(eve, 'GET', `/projects/${projectId}/tasks`)).statusCode).toBe(404); // not a member
    expect((await call(bob, 'POST', `/projects/${projectId}/members`, { email: 'eve@example.com' })).statusCode).toBe(403);
    expect((await rename(eve)).statusCode).toBe(404);
    expect((await rename(carol)).statusCode).toBe(403); // a member, but not the assignee
    expect((await rename(bob)).statusCode).toBe(200);
    expect((await rename(ada)).statusCode).toBe(200); // an admin
    expect((await call(ada, 'PATCH', `/tasks/${taskId}`, { assigneeId: eve.id })).statusCode).toBe(400);

    const comment = await call(carol, 'POST', `/tasks/${taskId}/comments`, { body: 'Looks good' });
    const commentUrl = `/comments/${comment.json<{ id: string }>().id}`;
    expect((await call(bob, 'GET', `/tasks/${taskId}/comments`)).json()).toHaveLength(1);
    expect((await call(eve, 'GET', `/tasks/${taskId}/comments`)).statusCode).toBe(404);
    expect((await call(ada, 'PATCH', commentUrl, { body: 'Edited by an admin' })).statusCode).toBe(403);
    expect((await call(carol, 'PATCH', commentUrl, { body: 'Looks great' })).statusCode).toBe(200);
  });

  it('moves a task once when ten moves from the same status race', async () => {
    const projectId = await createProject(ada, 'bob');
    const taskId = await createTask(ada, projectId, { assigneeId: bob.id });

    const results = await Promise.all(
      Array.from({ length: 10 }, (_, i) =>
        call(i % 2 ? ada : bob, 'POST', `/tasks/${taskId}/status`, { from: 'todo', to: i % 2 ? 'in_progress' : 'done' }),
      ),
    );

    expect(results.map((res) => res.statusCode).sort()).toEqual([200, ...Array(9).fill(409)]);
  });

  it('pages through tasks created at the same instant without gaps or repeats', async () => {
    const projectId = await createProject(ada);
    // One statement: all five rows get the same created_at.
    await db.insert(tasks).values(Array.from({ length: 5 }, (_, i) => ({ projectId, title: `Task ${i}`, description: '' })));

    const seen: string[] = [];
    let after = '';
    do {
      const res = await call(ada, 'GET', `/projects/${projectId}/tasks?limit=2${after && `&after=${after}`}`);
      const page = res.json<{ items: { id: string }[]; nextCursor: string | null }>();
      seen.push(...page.items.map((task) => task.id));
      after = page.nextCursor ?? '';
    } while (after);

    expect(new Set(seen).size).toBe(5);
    expect(seen).toHaveLength(5);
  });

  it("streams a project's changes to its members, and nobody else's", async () => {
    const [projectA, projectB] = [await createProject(ada, 'bob'), await createProject(ada)];
    const [taskA, taskB] = [await createTask(ada, projectA), await createTask(ada, projectB)];

    expect((await fetch(`${await app.getUrl()}/projects/${projectA}/events`, { headers: eve.headers })).status).toBe(404);

    const stream = await openStream(bob, projectA);
    await stream.readUntil(': connected');
    // A change in a project Bob isn't in, then one in his.
    await call(ada, 'PATCH', `/tasks/${taskB}`, { title: 'Not for Bob' });
    await call(ada, 'PATCH', `/tasks/${taskA}`, { title: 'For Bob' });

    const received = await stream.readUntil(`"id":"${taskA}"`);
    expect(received).toContain('event: task.updated');
    expect(received).not.toContain(taskB);
  });

  it('reminds each assignee once, however many runs overlap', async () => {
    const job = app.get(RemindersJob);
    await job.sendReminders(); // takes the job's lease: from here on, every call on this instance runs
    const projectId = await createProject(ada, 'bob');
    const dueAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();
    await createTask(ada, projectId, { assigneeId: bob.id, dueAt });
    const doneTask = await createTask(ada, projectId, { assigneeId: bob.id, dueAt });
    await call(bob, 'POST', `/tasks/${doneTask}/status`, { from: 'todo', to: 'done' });

    const sent = await Promise.all([1, 2, 3].map(() => job.sendReminders()));

    expect(sent.reduce((sum, count) => sum + count, 0)).toBe(1);
    expect(await job.sendReminders()).toBe(0);
  });

  /** Opens a project's event stream as `client`. */
  async function openStream(client: Client, projectId: string) {
    const controller = new AbortController();
    // Closed when the test ends, pass or fail: an open response would keep app.close() waiting.
    onTestFinished(() => controller.abort());
    const url = `${await app.getUrl()}/projects/${projectId}/events`;
    const res = await fetch(url, { headers: client.headers, signal: controller.signal });
    const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
    let received = '';
    return {
      /** Reads until `text` has arrived, and returns everything received. */
      async readUntil(text: string) {
        while (!received.includes(text)) {
          const { value, done } = await reader.read();
          if (done) {
            throw new Error('The stream ended');
          }
          received += value;
        }
        return received;
      },
    };
  }
});
Enter fullscreen mode Exit fullscreen mode
  • Each test user gets its own IP address, like real users would, since sign-up is capped at 10 per hour per IP and every route at 100 per minute.
  • The cron is switched off via SchedulerRegistry (see Dynamic cron jobs). The test then decides when the job runs, and a tick landing on a minute boundary can't grab the test's tasks first. The test's first call acquires the lease, and from then on every call on this instance actually runs, so the three parallel calls genuinely overlap.
  • Every stream is aborted when its test finishes, whether the test passed or failed. Otherwise the open response would block app.close().

The other test file is the JWT API's contract test for the refresh-token store. With concurrent: true, authenticationStoreContract() hits the store with parallel calls over a real pool, so a store that reads first and writes second fails:

// test/refresh-token.store.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { AuthenticationStorage } from '@nestjs/authentication';
import { authenticationStoreContract } from '@nestjs/authentication/testing';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { DrizzleRefreshTokenStore } from '../src/auth/drizzle-refresh-token.store.js';

// A real PostgreSQL with a pool, where parallel calls really race.
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('DrizzleRefreshTokenStore', () => {
  const pool = new Pool({ connectionString: url });
  const db = drizzle({ client: pool });

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
  });
  afterAll(() => pool.end());

  /** The store on an empty table, registered nowhere: the suite builds its own registry. */
  async function emptyStore() {
    await pool.query('TRUNCATE refresh_tokens');
    return { refreshTokens: new DrizzleRefreshTokenStore(db, new AuthenticationStorage()) };
  }

  for (const c of authenticationStoreContract(emptyStore, { contracts: ['refreshTokens'], concurrent: true })) {
    it(c.name, c.run);
  }
});
Enter fullscreen mode Exit fullscreen mode

Because the tests truncate tables, they get a separate database. Run the two files sequentially:

$ docker exec projects-db psql -U postgres -c "CREATE DATABASE projects_test"
$ TEST_DATABASE_URL=postgres://postgres:projects@localhost:5432/projects_test npm run test:e2e -- --no-file-parallelism

 Test Files  2 passed (2)
      Tests  10 passed (10)
Enter fullscreen mode Exit fullscreen mode

The ten tests are the refresh-token contract's five cases and the five tests in projects.e2e-spec.ts, run on Node 24 with @nestjs/core 12.5.1 and PostgreSQL 17.

To make sure the tests can actually fail, four of the guarantees were also broken on purpose, one at a time. With move() checking the status that load() had read instead of putting it in the UPDATE, three out of ten moves came back 200 in that run, and "moves a task once" failed. With created_at at PostgreSQL's default precision, the paging test saw only two of the five tasks. With the reminder claim split into a SELECT and an UPDATE, one task got three reminders. And with the project filter removed from the stream, the other project's event reached Bob.

Production checklist

The JWT API's production checklist still applies in full. In short: run with NODE_ENV=production, keep JWT_SECRET in your platform's secret store, run drizzle-kit migrate as a release step, set CORS_ORIGINS, collect the JSON logs from stdout, give the throttler shared storage once there's more than one instance, pass trustProxy to NodeAdapter behind a load balancer, size servers for scrypt, and point your platform's probes at the health checks. This API adds a few items of its own:

  • Share events across instances. EventEmitter2 only works inside one process. With two instances, a change saved on the first never reaches streams connected to the second. The fix is a channel all instances share, between the services that emit and the streams that listen: PostgreSQL's LISTEN/NOTIFY works, so does Redis pub/sub. Each instance still keeps its own Subject.
  • Refetch after reconnecting. An event is sent to whichever streams are open right then, and isn't kept anywhere, so a client that dropped off for a minute lost that minute's events. EventSource reconnects on its own; make the client reload the task list when it does.
  • Know what your proxy does to long responses. Nest sets X-Accel-Buffering: no, and the 20-second keep-alive comment stops idle timeouts, but a load balancer with a shorter idle timeout will still drop the connection, and one that buffers responses will hold events back. Also remember that each open stream is a connection: budget one connection per open browser tab when you set the proxy's and the server's limits.
  • Run with NODE_ENV=production, for the locks too. In production mode, LocksModule won't start unless a lock store is registered, just as the authentication module insists on its refresh-token store. Otherwise every job would quietly run on every instance.
  • Put the lock store's contract suite in CI. lockStoreContract() in @nestjs/locks/testing verifies every rule of the store contract, including the races when you pass concurrent: true, on the same PostgreSQL version you run in production.
  • Be careful when removing members. As long as a member has tasks assigned, the assignee foreign key won't let you delete their membership. Unassign their tasks in the same transaction that removes them, and close any streams they have open, since a stream checks membership only once, at connect time.
  • Give production its own Observe key pair. I create one on the project's API Keys page and set it as OBSERVE_APP_KEY and OBSERVE_APP_SECRET in the platform's environment, because start:prod doesn't load .env. NestJS Observe then records latency for every route, average and p95, so a combination of filters that misses its index shows up as a slow GET /projects/:projectId/tasks. It records each cron run as a job, with duration and outcome, and a job silence alert fires once the reminder job stops reporting. A scheduler that crashed will never tell you that itself (see Knowing a cron job actually ran).

Where to go from here

  • Let admins invite someone who has no account yet, with a single-use token sent by email: Mail.
  • Turn the reminder log line into a real email with retries, using Mail and Queues.
  • Let users reorder tasks within a column or move them to another project; each of those is a conditional update in the style of move().
  • Find out which routes and jobs are slow in production, one request at a time, with Observability.
  • Reuse the same foundation for a shop: Build an e-commerce backend.

Most of this API is CRUD, and in Nest the CRUD part is short: a schema for each request, a policy for each kind of record, a service, a controller. The code worth a second read is the handful of statements that decide what happens when people collide: the conditional move(), the cursor, and the claim in the reminder job each have a test that failed when they were broken, and the guard is what makes the stream answer a non-member with a real 404.

The docs version of this article, with every file and kept up to date, is Build a project-management API in Node.js.

Top comments (1)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

Reassigning a task skips the reminder. update() only clears remindedAt when dueAt is in the PATCH, so if Bob already got his reminder and the card goes to Carol 20 hours before the deadline, Carol never hears about it. I ran the claim statement against PG17 and tick two after the reassign returned nothing. Clearing it on an assignee change too fixed it:

remindedAt: dto.dueAt !== undefined || dto.assigneeId !== undefined ? null : undefined,
Enter fullscreen mode Exit fullscreen mode