Load Balancing

The Getting Started tutorials are contributed by API7.ai.

Load balancing manages traffic between clients and servers. It is a mechanism used to decide which server handles a specific request, allowing for improved performance, scalability, and reliability. Load balancing is a key consideration in designing systems that need to handle a large volume of traffic.

Apache APISIX supports weighted round-robin load balancing, in which incoming traffic are distributed across a set of servers in a cyclical pattern, with each server taking a turn in a predefined order.

In this tutorial, you will create a route with two upstream services and enable round-robin load balancing to distribute traffic between the two services.

Prerequisite(s)

  1. Complete Get APISIX to install APISIX.
  2. Understand APISIX Route and Upstream.

Enable Load Balancing

Let’s create a route with two upstream services. All requests sent to the /headers endpoint will be forwarded to httpbin.org and mock.api7.ai, which should echo back the requester’s headers.

  1. curl -i "http://127.0.0.1:9180/apisix/admin/routes" -X PUT -d '
  2. {
  3. "id": "getting-started-headers",
  4. "uri": "/headers",
  5. "upstream" : {
  6. "type": "roundrobin",
  7. "nodes": {
  8. "httpbin.org:443": 1,
  9. "mock.api7.ai:443": 1
  10. },
  11. "pass_host": "node",
  12. "scheme": "https"
  13. }
  14. }'

You will receive an HTTP/1.1 201 Created response if the route was created successfully.

Load Balancing - 图1info
  1. The pass_host field is set to node to pass the host header to the upstream.
  2. The scheme field is set to https to enable TLS when sending requests to the upstream.

Validate

The two services respond with different data.

From httpbin.org:

  1. {
  2. "headers": {
  3. "Accept": "*/*",
  4. "Host": "httpbin.org",
  5. "User-Agent": "curl/7.58.0",
  6. "X-Amzn-Trace-Id": "Root=1-63e34b15-19f666602f22591b525e1e80",
  7. "X-Forwarded-Host": "localhost"
  8. }
  9. }

From mock.api7.ai:

  1. {
  2. "headers": {
  3. "accept": "*/*",
  4. "host": "mock.api7.ai",
  5. "user-agent": "curl/7.58.0",
  6. "content-type": "application/json",
  7. "x-application-owner": "API7.ai"
  8. }
  9. }

Let’s generate 100 requests to test the load-balancing effect:

  1. hc=$(seq 100 | xargs -I {} curl "http://127.0.0.1:9080/headers" -sL | grep "httpbin" | wc -l); echo httpbin.org: $hc, mock.api7.ai: $((100 - $hc))

The result shows the requests were distributed over the two services almost equally:

  1. httpbin.org: 51, mock.api7.ai: 49

What’s Next

You have learned how to configure load balancing. In the next tutorial, you will learn how to configure key authentication.