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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps

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