Round Robin
Định nghĩa
Thuật toán Round Robin phân phối yêu cầu theo vòng tuần tự:
index = (index + 1) % NTrong đó:
Nlà số server (hoặc worker/task consumer)indexlà chỉ số server hiện tại
Pseudo Code chuẩn
servers = [S1, S2, S3, S4]
current = 0
function getServer():
server = servers[current]
current = (current + 1) mod length(servers)
return serverGolang Implementation
Điểm quan trọng:
Dùng
sync.Mutexđể tránh race condition khi chạy multi-goroutine.
Java Implementation
Điểm hay:
Dùng
AtomicInteger→ thread-safe → tránh synchronization nặng.
Biến thể: Weighted Round Robin
Cho phép máy mạnh nhận nhiều request hơn.
Server
Weight
S1
5
S2
1
Cách expand list đơn giản:
Hoặc dùng thuật toán Smooth Weighted Round Robin (ngon hơn, Kubernetes/Envoy/nginx đều dùng).
TL;DR (gist)
Round Robin quay vòng: index = (index + 1) % N
Thread-safe Golang dùng
sync.MutexThread-safe Java dùng
AtomicIntegerThích hợp stateless service; không phù hợp long-lived connections.
Weighted Round Robin = phân tải theo trọng số.
Last updated