How To Measure Your Server's Round-trip Time In Remix (React)

Peter Mbanugo - May 26 '23 - - Dev Community

Problem

In the world of web development, every millisecond counts. Web developers are constantly driven to achieve maximum speed and efficiency. They meticulously measure round-trip time (RTT) and other related metrics to understand page load time and network latency. However, there's a challenge: the further our server is from the user, the longer it takes to respond. So, how do we tackle this hurdle and measure network latency accurately?

Latency Diagram

Solution

We can measure the full network transfer time between the browser and the Remix server by calculating the difference between when the request was made from the browser, and when a response was gotten from the server. We can achieve this by creating a function that makes a request to a resource and calculates the time (in milliseconds) it takes to fulfil it. We'll add a page that executes that function every second and the result will be displayed in the browser.

Sounds too theoretical? Let's get started with the code 👨🏽‍💻

We're going to start by defining the function that pings the server and calculates the duration. Add the following pingServer() function to your code. You can choose to put it anywhere you prefer, for example, in a separate file called ping.js.



const pingServer = async () => {
  try {
    const startTime = new Date().getTime();
    await fetch("/ping");
    const endTime = new Date().getTime();
    const responseTime = endTime - startTime;

    return `Server responded in ${responseTime}ms`;
  } catch (error) {
    console.error("Ping failed:", error);
    return "Ping failed";
  }
};


Enter fullscreen mode Exit fullscreen mode

The pingServer() function calls the /ping route, calculates the duration, and returns a message that contains the measured time. If the server can't be reached, then an error message is returned.

Next, we're going to add a /ping resource route that returns an empty HTTP response. Add a new file /routes/ping.js and paste the code snippet below into it.



export async function loader() {
  return new Response(null, {
    status: 200,
    headers: {
      "Cache-Control": "no-store",
    },
  });
}


Enter fullscreen mode Exit fullscreen mode

Finally, add a page that would display a button to trigger the pingServer() function and display the result in the browser.



export default function Index() {
  const [message, setMessage] = useState("");
  return (
    <div>
      <h1>Ping Test</h1>
      <button
        disabled={message !== ""}
        onClick={async () => {
          setInterval(async () => {
            setMessage(await pingServer());
          }, 1000);
        }}
      >
        Click to start ping
      </button>
      <p>{message}</p>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

That's all you need to add a page that constantly pings the server and calculates the round-trip time.

Let's see our solution in action! The GIF below shows me running my Remix app with the ping time measured and displayed in the browser.

Demo - calculate ping time

Conclusion

You've seen how to measure and display the latency for your Remix application. You can use that page for diagnostic purposes with your users or as a support engineer. When you have the needed data, the next step is to decide how to improve the user experience and decrease latency. That begs the question; Are there ways to ensure a lightning-fast web experience, regardless of distance?

Regarding latency, one solution would be to distribute the servers geographically closer to your users. How you achieve that would vary depending on how you're hosting the application. I'll discuss more about this solution in my next post, so stay tuned 😎

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .