Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 27: Cache trong NestJS

Tiếp tục với series, mỗi lần mở trang tổng quan, TaskFlow lại đếm task trong database dù số liệu ít đổi. Bài này mình sẽ giới thiệu với mọi người về cache trong NestJS qua tính năng thống kê task.

1. Cache và CacheModule.

Cache là nơi lưu tạm kết quả đã tính để lần sau trả ngay, không phải query lại. NestJS hỗ trợ cache qua @nestjs/cache-manager (12.0.5), bên dưới là cache-manager 7 dùng Keyv:

npm install @nestjs/cache-manager cache-manager

- src/app.module.ts (đoạn trích trong imports; import CacheModule từ @nestjs/cache-manager)

        // Cache dùng chung cho mọi module, mặc định hết hạn sau 60 giây
        CacheModule.register({ isGlobal: true, ttl: 60_000 }),

ttl (time to live) là thời gian sống của mỗi mục tính bằng mili giây, không đặt thì không bao giờ hết hạn. Mặc định cache nằm trong bộ nhớ của process (phần 5 chuyển sang Redis).

2. CacheInterceptor và TTL.

Route mới GET /api/v1/projects/:id/stats trả số task theo trạng thái (service và kiểu ProjectStats ở phần 3). Cách nhanh nhất là gắn CacheInterceptor (Bài 13): lần sau handler không chạy, kết quả lấy từ cache.

- src/projects/projects.controller.ts (đoạn trích; CacheInterceptor từ @nestjs/cache-manager, UseInterceptors từ @nestjs/common)

    @Get(':id/stats')
    @UseInterceptors(CacheInterceptor)
    stats(
        @Param('id', ParseIdPipe) id: number,
        @CurrentUser() user: AuthUser,
    ): Promise<ProjectStats> {
        return this.projectsService.stats(id, user.id);
    }

Reset dữ liệu như Bài 22, đăng ký An (token $B), tai ($A) tạo task 1 (todo), task 2 (doing) trong project 1. Header X-Cache cho biết có lấy từ cache không:

curl -i http://localhost:3000/api/v1/projects/1/stats -H "$A"
# X-Cache: MISS
# {"data":{"projectId":1,"total":2,"todo":1,"doing":1,"done":0,"computedAt":"2026-11-15T11:09:04.748Z"}}
curl -i http://localhost:3000/api/v1/projects/1/stats -H "$B"
# X-Cache: HIT
# {"data":{...,"computedAt":"2026-11-15T11:09:04.748Z"}}  <- dữ liệu của tai

Chú ý: Key mặc định chỉ là URL. Cache trúng thì handler không chạy, không ai kiểm tra quyền, nên An đọc được thống kê của tai. Đừng gắn CacheInterceptor mặc định lên route cần đăng nhập hay đăng ký nó toàn cục.

Cách sửa là kế thừa CacheInterceptor và ghi đè trackBy() để key có id của user:

- src/common/interceptors/user-cache.interceptor.ts

import { CacheInterceptor } from '@nestjs/cache-manager';
import { ExecutionContext, Injectable } from '@nestjs/common';
import type { AuthRequest } from '../../auth/auth-user.js';

// Như CacheInterceptor nhưng mỗi user một bản cache riêng
@Injectable()
export class UserCacheInterceptor extends CacheInterceptor {
    protected trackBy(context: ExecutionContext): string | undefined {
        // Key mặc định: URL nếu là request GET, ngược lại undefined
        const url = super.trackBy(context);
        const user = context.switchToHttp().getRequest<AuthRequest>().user;
        // Không có user thì không cache
        if (typeof url !== 'string' || !user) {
            return undefined;
        }
        return `user:${user.id}:${url}`;
    }
}

Chỉ request GET được cache, response lỗi không được lưu. Route đổi thành @UseInterceptors(UserCacheInterceptor) kèm @CacheTTL(30_000) (ghi đè ttl của CacheModule).

Restart ứng dụng (xoá cache trong bộ nhớ) rồi thử lại: An nhận 404 PROJECT_NOT_FOUND kèm X-Cache: MISS. Còn một vấn đề: tai tạo thêm task 3 nhưng thống kê vẫn là "total":2 (HIT) cho tới khi hết 30 giây.

3. Cache thủ công.

Thống kê phải đổi ngay khi task đổi, nên mình tự quản lý cache trong service để biết key cần xoá. Bỏ @UseInterceptors, @CacheTTL khỏi route stats (giữ file UserCacheInterceptor cho route khác), rồi tạo:

- src/projects/project-stats.ts

// Số task theo trạng thái của một project
export interface ProjectStats {
    projectId: number;
    total: number;
    todo: number;
    doing: number;
    done: number;
    computedAt: string; // thời điểm tính, để thấy kết quả lấy từ cache
}

// Key có userId: user khác không bao giờ đọc được bản cache này
export function projectStatsKey(userId: number, projectId: number): string {
    return `stats:user:${userId}:project:${projectId}`;
}

- src/projects/projects.service.ts (đoạn trích; CACHE_MANAGER, type Cache từ @nestjs/cache-manager)

        // thêm vào constructor
        @Inject(CACHE_MANAGER) private readonly cache: Cache,

    async stats(id: number, userId: number): Promise<ProjectStats> {
        const key = projectStatsKey(userId, id);
        const cached = await this.cache.get<ProjectStats>(key);
        if (cached) {
            return cached; // có trong cache: không query database
        }
        const stats = await this.computeStats(id, userId);
        await this.cache.set(key, stats, 60_000); // hết hạn sau 60 giây
        return stats;
    }

computeStats() kiểm tra quyền như findOne() rồi đếm task theo status bằng groupBy() của Prisma:

    private async computeStats(
        id: number,
        userId: number,
    ): Promise<ProjectStats> {
        const owned = await this.prisma.project.count({
            where: { id, ownerId: userId },
        });
        if (owned === 0) {
            throw new ProjectNotFoundException(id);
        }
        const groups = await this.prisma.task.groupBy({
            by: ['status'],
            where: { projectId: id },
            _count: { _all: true },
        });
        const stats: ProjectStats = {
            projectId: id,
            total: 0,
            todo: 0,
            doing: 0,
            done: 0,
            computedAt: new Date().toISOString(),
        };
        for (const { status, _count } of groups) {
            stats[status] = _count._all;
            stats.total += _count._all;
        }
        return stats;
    }

Trong đó:

  • get() trả undefined khi không có key, set(key, value, ttl) lưu giá trị; còn có del(key), mdel(keys), clear().
  • Store trong bộ nhớ trả về chính object đã lưu: đừng sửa object lấy từ cache.
curl http://localhost:3000/api/v1/projects/1/stats -H "$A"
# {"data":{"projectId":1,"total":3,"todo":2,"doing":1,"done":0,"computedAt":"2026-11-15T11:10:54.840Z"}}
# Gọi lại sau vài giây: cùng computedAt. An gọi: 404

4. Xoá cache khi dữ liệu đổi.

Task được tạo, sửa, xoá thì thống kê phải tính lại:

- src/tasks/tasks.service.ts (đoạn trích; inject CACHE_MANAGER như trên)

    // Xoá cache thống kê sau khi đã ghi xong vào database
    private async clearStats(
        userId: number,
        ...projectIds: (number | undefined)[]
    ): Promise<void> {
        const keys = projectIds
            .filter((id) => id !== undefined)
            .map((id) => projectStatsKey(userId, id));
        await this.cache.mdel(keys);
    }

Trong đó:

  • create(), update(), remove() gọi await this.clearStats(userId, task.projectId) sau lệnh ghi (xoá trước thì request chen giữa có thể lưu lại số liệu cũ).
  • Task chuyển project: update() lấy projectId cũ bằng findOne() rồi xoá cả hai key. ProjectsService.remove() cũng xoá key tương tự. Mutation GraphQL dùng chung service nên cũng được xoá.
curl -X PATCH http://localhost:3000/api/v1/tasks/1 -H "$A" -H "Content-Type: application/json" -d '{"status":"done"}'
curl http://localhost:3000/api/v1/projects/1/stats -H "$A"
# {"data":{"projectId":1,"total":3,"todo":1,"doing":1,"done":1,"computedAt":"2026-11-15T11:10:57.298Z"}}

5. Dùng Redis làm cache store.

Cache trong bộ nhớ mất khi restart, và mỗi instance một cache: instance này xoá, instance khác vẫn trả số liệu cũ. Redis là nơi lưu chung:

docker run -d --name taskflow-redis -p 127.0.0.1:6379:6379 redis:8-alpine

npm install @keyv/redis

Như MONGODB_URI ở Bài 19, thêm REDIS_URL="redis://localhost:6379" vào .env, .env.example, envSchema (z.url({ protocol: /^rediss?$/ })), redisUrl vào database.config.ts, rồi thay CacheModule.register():

- src/app.module.ts (đoạn trích; createKeyv từ @keyv/redis, Logger từ @nestjs/common)

        // Cache dùng chung cho mọi module, lưu trên Redis
        CacheModule.registerAsync({
            isGlobal: true,
            inject: [databaseConfig.KEY],
            useFactory: (database: ConfigType<typeof databaseConfig>) => {
                const logger = new Logger('Cache');
                const redis = createKeyv(database.redisUrl);
                // Bắt buộc lắng nghe 'error': không có listener, lỗi Redis làm sập ứng dụng
                redis.on('error', (error) => logger.error('Lỗi Redis', error));
                return { stores: [redis], ttl: 60_000 };
            },
        }),

Service vẫn dùng CACHE_MANAGER nên không đổi gì. Redis lưu dạng JSON: Date lấy ra thành string, instance của class thành object thường (nên computedAt là string từ đầu).

# Gọi stats một lần rồi xem trong Redis
docker exec taskflow-redis redis-cli get stats:user:1:project:1
# {"value":{"projectId":1,...,"computedAt":"2026-11-15T11:14:27.208Z"},"expires":1794741327208}
# Restart ứng dụng rồi gọi lại: vẫn computedAt cũ, cache còn nguyên

Lưu ý: Từ giờ reset dữ liệu thì xoá luôn cache bằng docker exec taskflow-redis redis-cli flushall.

Chú ý: Redis dừng thì lệnh cache chờ kết nối lại, request bị TimeoutInterceptor trả 408 (log ghi Lỗi Redis), kể cả request tạo, sửa, xoá task dù dữ liệu đã được lưu (clearStats() chạy sau lệnh ghi): đừng tự gửi lại POST, sẽ tạo trùng task. Bài 29 sẽ sửa để lỗi cache không làm hỏng request.

6. Lời kết.

Như vậy mình đã giới thiệu xong về cache trong NestJS: CacheInterceptor theo user, cache thủ công, xoá cache và Redis store. Bài sau mình sẽ giới thiệu về gửi mail trong NestJS.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha