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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The @Cron decorator turns ordinary methods into scheduled jobs without any manual timer wiring.
- 2TypeORM's delete with a LessThan operator expresses time-based purges declaratively as a single query.
- 3Naming each cron and reading affected row counts makes scheduled cleanup observable and traceable.
Related explainers
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/scheduled-session-cleanup-in-nestjs-explained-typescript-c86a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.