Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 33: Microservices trong NestJS (Phần 2)

Tiếp tục với series, bài này là phần 2 về microservices trong NestJS. Service thông báo ở Bài 32 còn ba vấn đề: chạy hai instance thì gửi hai mail, gọi mail-stats lúc service tắt thì API trả 500, và service tắt thì event mất. Bài này mình sẽ sửa hai vấn đề đầu với NATS queue group và timeout, giải thích vì sao vấn đề thứ ba cần message bền, và giới thiệu pre-request hook.

1. Transport NATS.

NATS là message broker nhẹ: bên gửi publish message vào một subject (như user.registered), bên nhận subscribe subject đó. Khác Redis pub/sub, NATS có queue group: các subscriber cùng nhóm chia nhau message, mỗi message chỉ tới một thành viên.

Từ NestJS 12, transport NATS dùng NATS v3 với package @nats-io/transport-node thay cho package nats cũ (nâng cấp từ bản cũ thì npm uninstall nats). Mình cài package và chạy NATS server bằng Docker:

npm install @nats-io/transport-node
docker run -d --name taskflow-nats -p 4222:4222 nats:2-alpine

Request-response cũng đi qua NATS nên mình bỏ TCP: biến NOTIFICATIONS_HOST, NOTIFICATIONS_PORT thay bằng NATS_URL (mặc định nats://localhost:4222), config notifications chỉ còn natsUrl. Xoá redis-options.ts cùng các import databaseConfig, redisOptions trong notification-service/main.ts và notifications.module.ts.

2. Chuyển service thông báo sang NATS.

Bên service, hai lần connectMicroservice() gộp thành một:

- src/notification-service/main.ts (đoạn trích, thay phần Redis và TCP ở Bài 32)

    const notifications = app.get<ConfigType<typeof notificationsConfig>>(
        notificationsConfig.KEY,
    );
    const nats = app.connectMicroservice<MicroserviceOptions>(
        {
            transport: Transport.NATS,
            options: {
                servers: [notifications.natsUrl],
                // Queue group: mỗi message chỉ tới MỘT instance trong nhóm
                queue: 'notification-service',
                maxReconnectAttempts: -1, // NATS sập lâu vẫn kết nối lại
            },
        },
        // deferInitialization: listener được tạo ở startAllMicroservices(),
        // nhờ vậy pre-request hook bên dưới mới được áp dụng
        { inheritAppConfig: true, deferInitialization: true },
    );

Trong đó:

  • servers: danh sách NATS server.
  • queue: tên queue group, áp dụng cho mọi handler của service.
  • maxReconnectAttempts: -1: thử kết nối lại mãi mãi. Mặc định thư viện chỉ thử 10 lần, cách nhau 2 giây, rồi bỏ cuộc.

Trong NotificationController, các decorator bỏ tham số transport: @EventPattern(USER_REGISTERED), @MessagePattern(MAIL_STATS). Bên API, NotificationsModule chỉ còn một client cho cả emit() lẫn send():

- src/notifications/notifications.module.ts (đoạn trích phần imports)

        // Một ClientProxy NATS cho cả event (emit) lẫn request-response (send)
        ClientsModule.registerAsync([
            {
                name: NOTIFICATION_CLIENT,
                inject: [notificationsConfig.KEY],
                useFactory: (
                    notifications: ConfigType<typeof notificationsConfig>,
                ) => ({
                    transport: Transport.NATS,
                    options: { servers: [notifications.natsUrl] },
                }),
            },
        ]),

NotificationsService inject nó bằng @Inject(NOTIFICATION_CLIENT) thay cho hai token cũ.

3. Queue group và độ bền của message.

Reset dữ liệu như Bài 31, chạy npm run build, rồi API (npm run start:prod) và hai instance service (npm run start:notifications:prod), mỗi lệnh một terminal. Đăng ký 4 user:

for n in 1 2 3 4; do
    curl -s -o /dev/null -w "%{http_code} " -X POST http://localhost:3000/api/v1/auth/register \
        -H "Content-Type: application/json" \
        -d "{\"name\":\"User$n\",\"email\":\"[email protected]\",\"password\":\"matkhau123\"}"
done
# 201 201 201 201
# Mailpit nhận đúng 4 mail chào mừng, mỗi event chỉ một instance xử lý

Không còn mail trùng; mail.stats cũng chỉ một instance trả lời.

Tuy vậy NATS core vẫn là at most once: tắt cả hai instance rồi đăng ký Bình, API vẫn trả 201 nhưng bật service lại cũng không có mail. Muốn message bền (không mất khi bên nhận tắt) thì cần nơi lưu nó:

  • JetStream của NATS: lưu message vào stream, bên nhận xác nhận (ack) xong mới xoá. Transport NATS của NestJS không dùng JetStream, phải tự viết consumer.
  • Hoặc API đưa job thẳng vào queue BullMQ (Bài 29) trong Redis, service chỉ làm worker. Job nằm trong Redis tới khi được xử lý.

Không chỉ mail chào mừng: mail task.assigned và cả lô nhắc việc 08:00 cũng mất, vì reminders.due chỉ emit một lần và emit() vẫn thành công khi không ai subscribe. Service tắt hoặc đang deploy lúc đó là cả ngày không có mail nhắc. TaskFlow chấp nhận rủi ro này để giữ NATS core cho gọn; nếu nhắc việc quan trọng thì nên để API đưa job vào BullMQ.

4. Xử lý lỗi và timeout.

send() có thể lỗi vì không ai nghe subject, mất kết nối NATS, service ném lỗi, hoặc service treo. Mặc định các lỗi thành 500, còn service treo thì request chờ tới khi TimeoutInterceptor (Bài 13) trả 408. Mình thêm operator timeout của RxJS và đổi lỗi sang mã HTTP rõ nghĩa:

- src/common/utils/rpc-to-http.ts

import {
    BadGatewayException,
    type HttpException,
    ServiceUnavailableException,
} from '@nestjs/common';

// Lỗi khi gọi microservice bằng send() -> lỗi HTTP rõ nghĩa thay cho 500
export function rpcToHttpException(error: unknown): HttpException {
    // Service đã nhận message nhưng xử lý lỗi (RpcException hoặc lỗi khác):
    // client nhận object { status: 'error', message }
    if (
        typeof error === 'object' &&
        error !== null &&
        'status' in error &&
        error.status === 'error'
    ) {
        return new BadGatewayException('Service thông báo xử lý lỗi');
    }
    // TimeoutError, không ai nghe (EmptyResponseException), mất kết nối NATS...
    return new ServiceUnavailableException(
        'Service thông báo tạm thời không phản hồi',
    );
}

- src/notifications/notifications.service.ts (đoạn trích; import thêm catchError, throwError, timeout từ rxjs và rpcToHttpException từ ../common/utils/rpc-to-http.js)

    mailStats(): Promise<MailStats> {
        return firstValueFrom(
            this.client.send<MailStats>(MAIL_STATS, {}).pipe(
                timeout(3000), // quá 3 giây chưa trả lời: TimeoutError
                catchError((error: unknown) => {
                    this.logger.error(`Không gọi được ${MAIL_STATS}`, error);
                    return throwError(() => rpcToHttpException(error));
                }),
            ),
        );
    }

Timeout 3 giây phải nhỏ hơn REQUEST_TIMEOUT (5 giây). Lỗi gốc chỉ ghi log, client không thấy chi tiết. Chạy thử với token của tai ($A):

# Tắt hết service: NATS báo không ai nghe, lỗi trả về ngay
curl http://localhost:3000/api/v1/notifications/mail-stats -H "$A"
# {"statusCode":503,"errorCode":"SERVICE_UNAVAILABLE","message":"Service thông báo tạm thời không phản hồi",...}
# log: Empty response. There are no subscribers listening to that message ("mail.stats")

# Bật service, tắt Redis: getJobCounts() treo, sau 3 giây
# 503, log: TimeoutError "Timeout has occurred"

Còn khi handler của service ném lỗi thì API trả 502 "Service thông báo xử lý lỗi". Với emit() thì lỗi phía service chỉ nằm trong log của service.

5. Pre-request hook.

Pre-request hook là tính năng mới ở NestJS 12: hàm chạy trước guard, interceptor và pipe của mọi message handler, giống middleware của HTTP. Hook nhận ExecutionContext và next, phải trả về Observable của next() (hoặc bọc nó). Mình dùng hook để ghi log thời gian xử lý từng message:

- src/notification-service/main.ts (đoạn trích, ngay sau connectMicroservice(); import thêm Logger từ @nestjs/common, type NatsContext từ @nestjs/microservices, finalize từ rxjs)

    // Chạy trước guard, interceptor, pipe của mọi handler (như middleware)
    const logger = new Logger('NATS');
    nats.registerPreRequestHook((context, next) => {
        const subject = context
            .switchToRpc()
            .getContext<NatsContext>()
            .getSubject();
        const start = Date.now();
        return next().pipe(
            finalize(() =>
                logger.log(`${subject} xử lý xong sau ${Date.now() - start}ms`),
            ),
        );
    });
    await app.init(); // không gọi listen(): không mở cổng HTTP
    await app.startAllMicroservices();

Đăng ký An rồi gọi mail-stats, log của service có:

{"level":"log",...,"context":"NATS","message":"user.registered xử lý xong sau 20ms"}
{"level":"log",...,"context":"NATS","message":"mail.stats xử lý xong sau 4ms"}

Lưu ý: Hook phải đăng ký trước khi microservice khởi tạo. Trong hybrid application, connectMicroservice() khởi tạo ngay, nên cần deferInitialization: true, nếu không hook bị bỏ qua. Hook gọi trên object connectMicroservice() trả về. Quên gọi next() thì handler không chạy.

6. Khi nào nên tách microservice.

Tách service thông báo cho TaskFlow chủ yếu để học. Thực tế nên tách khi:

  • Phần đó cần scale riêng (gửi mail, xử lý ảnh chạy nặng hơn hẳn API).
  • Các team khác nhau phát triển và deploy độc lập.
  • Cần cô lập lỗi: service sập không kéo API sập theo.

Không nên tách khi team nhỏ, nghiệp vụ còn đổi nhiều, hoặc các phần vẫn dùng chung database (service thông báo vẫn đọc PostgreSQL của API: chưa tách thật sự). Microservice kéo theo broker, nhiều process, lỗi mạng, message mất. Cách an toàn là bắt đầu bằng monolith chia module rõ ràng (Bài 4), khi cần mới tách.

7. Lời kết.

Như vậy mình đã giới thiệu xong phần 2 về microservices trong NestJS: NATS với queue group, giới hạn của NATS core, timeout, pre-request hook và khi nào nên tách service. Bài sau mình sẽ giới thiệu về testing trong NestJS với Vitest.

Đă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