typescript 40 lines · 7 steps

Scheduled session cleanup in NestJS

A NestJS service runs two cron jobs that delete expired and stale sessions from the database on a schedule.

Explained by highlit
1import { Injectable, Logger } from '@nestjs/common';
2import { Cron, CronExpression } from '@nestjs/schedule';
3import { InjectRepository } from '@nestjs/typeorm';
4import { Repository, LessThan } from 'typeorm';
5import { Session } from './entities/session.entity';
6 
7@Injectable()
8export class SessionCleanupService {
9 private readonly logger = new Logger(SessionCleanupService.name);
10 
11 constructor(
12 @InjectRepository(Session)
13 private readonly sessions: Repository<Session>,
14 ) {}
15 
16 @Cron(CronExpression.EVERY_HOUR, { name: 'expired-session-cleanup' })
17 async removeExpiredSessions(): Promise<void> {
18 const cutoff = new Date();
19 
20 const { affected } = await this.sessions.delete({
21 expiresAt: LessThan(cutoff),
22 });
23 
24 if (affected) {
25 this.logger.log(`Purged ${affected} expired session(s)`);
26 }
27 }
28 
29 @Cron('0 3 * * 0', { name: 'stale-session-cleanup', timeZone: 'UTC' })
30 async removeStaleSessions(): Promise<void> {
31 const threshold = new Date();
32 threshold.setDate(threshold.getDate() - 30);
33 
34 const { affected } = await this.sessions.delete({
35 lastSeenAt: LessThan(threshold),
36 });
37 
38 this.logger.log(`Weekly sweep removed ${affected ?? 0} stale session(s)`);
39 }
40}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The @Cron decorator turns ordinary methods into scheduled jobs without any manual timer wiring.
  2. 2TypeORM's delete with a LessThan operator expresses time-based purges declaratively as a single query.
  3. 3Naming each cron and reading affected row counts makes scheduled cleanup observable and traceable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Scheduled session cleanup in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code