TCP latency test implementation details

Server side

This server runs nginx with lua support (nginx-extras in Debian).

Nginx config

location = /rtt.json {
	if ($http_origin) {
		add_header 'Access-Control-Allow-Origin' 'https://openspeedtest.com';
		add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
	}
	if ($request_method = OPTIONS ) {
		add_header Access-Control-Allow-Credentials "true";
		add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
		add_header Access-Control-Allow-Origin "https://openspeedtest.com";
		add_header Access-Control-Allow-Methods "GET, OPTIONS";
		return 204;
	}
	content_by_lua_file /path/to/rtt.lua;
}

Lua code

The Lua code just exposes a few internal TCP_INFO variables from nginx.

local rtt = ngx.var.tcpinfo_rtt
local rttvar = ngx.var.tcpinfo_rttvar
local reqs = ngx.var.connection_requests
ngx.header.content_type = 'text/json'
ngx.header['Cache-Control'] = 'no-cache, no-store, must-revalidate'
ngx.header['Pragma'] = 'no-cache'
ngx.header['Expires'] = '0'
ngx.say(string.format('{"rtt":%d,"rttvar":%d,"reqs":%d}', rtt, rttvar, reqs))

Testing with curl

$ for i in $(seq 1 10); do echo https://speed.fiberby.dk/rtt.json; done | xargs curl
{"rtt":1000,"rttvar":500,"reqs":1}
{"rtt":972,"rttvar":430,"reqs":2}
{"rtt":973,"rttvar":325,"reqs":3}
{"rtt":966,"rttvar":259,"reqs":4}
{"rtt":968,"rttvar":198,"reqs":5}
{"rtt":959,"rttvar":165,"reqs":6}
{"rtt":962,"rttvar":130,"reqs":7}
{"rtt":966,"rttvar":104,"reqs":8}
{"rtt":963,"rttvar":83,"reqs":9}
{"rtt":956,"rttvar":77,"reqs":10}