Setting up load balancing for a React app with a Gleam backend

OtherHendo
Sign in to confirm0 confirmations

Question

How to configure load balancing for a React application with a Gleam backend, ensuring efficient distribution of incoming traffic across multiple Gleam server instances.

Answer

To achieve load balancing for a React app with a Gleam backend, understand that the load balancer sits entirely on the backend and intercepts requests from the React app. Set up multiple independent instances of the Gleam web server on different internal ports or separate servers, then place a reverse proxy like Nginx or Caddy in front of these instances. The proxy distributes incoming traffic across the Gleam instances. Finally, point the React application's HTTP requests to the single URL exposed by the load balancer.

nginx
upstream gleam_backend {
    # The list of your running Gleam servers
    server 127.0.0.1:4001;
    server 127.0.0.1:4002;
    server 127.0.0.1:4003;
}

server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://gleam_backend;
        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;
    }
}
typescript
import { useEffect, useState } from 'react';

export function UserProfile() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // You point to the Load Balancer endpoint, NOT the individual Gleam ports
    fetch('https://api.yourdomain.com/users/profile')
      .then((res) => res.json())
      .then((data) => setData(data));
  }, []);

  return <div>{data ? `Welcome, ${data.name}` : "Loading..."}</div>;
}
typescriptreactgleamnginxloadbalancing