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) % N

Trong đó:

  • N là số server (hoặc worker/task consumer)

  • index là 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 server

Golang 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.Mutex

  • Thread-safe Java dùng AtomicInteger

  • Thí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