Sử dụng mirror module của Nginx để nhân bản request sang một server thứ 2
Trong quá trình làm việc, tụi mình gặp một case thực tế trong quá trình migration hệ thống. Yêu cầu mirror request đang gọi vào hệ thống cũ sang hệ thống mới để A/B Testing
Ok, sau khi tìm hiểu tụi mình quyết định sử dụng mirror module của nginx để giải quyết vấn đề trên. Mô hình triển khai như dưới:

Trước khi đi vào cấu hình chi tiết, mình sẽ tìm hiểu một số khái niệm
1. Nginx Mirror Module hoạt động như thế nào?
- Khác với reverse proxy, mirror hoạt động:
- Không trả response từ luồng mirror
- không chờ mirror xử lý xong
- Chỉ copy request sang server khác
- Response trả về vẫn là từ server chính
- Khi luồng mirror lỗi thì không làm request chính fail
2. Khi nào nên dùng mirror
- Gửi log realtime sang server khác
- Gửi dữ liệu audit
- Gửi message sang hệ thống backup
- A/B testing
- Đồng bộ message queue
- Gửi webhook duplicate
3. Đi vào bài toán cụ thể
- Tụi mình chỉ cần mirror traffic của 1 số endpoint cụ thể thay vì mirror tất cả các traffic sang cụm application 2.
- File cấu hình nginx sử dụng
server {
listen 8888;
server_name _;
# ========================
# 1. /api/updatePackage
# ========================
location /api/updatePackage {
mirror /mirror_updatePackage;
mirror_request_body on;
proxy_pass http://127.0.0.1:9999;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# ========================
# 2. /api/forwardMessage
# ========================
location /api/forwardMessage {
mirror /mirror_forwardMessage;
mirror_request_body on;
proxy_pass http://127.0.0.1:9999;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# ========================
# 3. Root /
# ========================
location / {
# Chỉ proxy, không mirror
proxy_pass http://127.0.0.1:9999; # Application 1
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# ========================
# Mirror internal locations
# ========================
location /mirror_updatePackage {
internal;
proxy_pass http://10.10.1.5:8081; # Application 2
proxy_pass_request_body on;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /mirror_forwardMessage {
internal;
proxy_pass http://10.10.1.5:8081; # Application 2
proxy_pass_request_body on;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Ngày đi làm cuối của năm 2025. Chúc mừng năm mới A/E.
All rights reserved