System Design (High-Level Design) Module 2 – Back-of-the-envelope estimation
Latency numbers, measured on real hardware
Order operations from nanoseconds to hundreds of milliseconds, measure memory, SQLite and disk latency with scripts, and work out the speed-of-light floor.
What you will learn
- Order common operations by latency, from a memory lookup to a round trip between continents
- Measure lookups, database reads and durable disk writes with documented scripts
- Work out how a flush time caps durable writes a second, and how group commit lifts the cap
- Explain why a latency table copied without its hardware, software and method misleads
- Calculate the speed-of-light floor of a network round trip between two places
Before you start
What you’ll learn · Before you start
What you will learn
- Order common operations by latency, from a memory lookup to a round trip between continents
- Measure lookups, database reads and durable disk writes with documented scripts
- Work out how a flush time caps durable writes a second, and how group commit lifts the cap
- Explain why a latency table copied without its hardware, software and method misleads
- Calculate the speed-of-light floor of a network round trip between two places
Before you start
On this page
A design is mostly decided by orders of magnitude. If a page must load in 200 milliseconds, it cannot make ten calls one after another to a server on another continent, and no amount of tuning will change that. A cache in the same process answers in nanoseconds to microseconds, while a cache in another data centre costs a network round trip of milliseconds before it answers anything. You do not need exact values to see this, but you do need the right order of magnitude for each operation, and the safest way to get it is to measure.
This lesson measures a few operations on a real machine, shows the method next to every number, and works out the one latency that no hardware can improve: the time light takes to cover the distance.
Latency comes in rungs, each 10 to 1,000 times slower than the last
Each of the first three rungs is about a thousand times slower than the one above it, and the last is ten to a hundred times slower again: every step down the ladder is at least one order of magnitude: A factor of ten. Two quantities are an order of magnitude apart when one is about ten times the other; a microsecond and a millisecond are three orders apart.. The examples on each rung are the ones this lesson measures or computes.
The latency ladder, with operations this lesson measures
Text description of the diagram
The diagram is a ladder of four rungs, read from top to bottom. Each rung is a unit of time with examples from this lesson.
- Nanoseconds: a Python dictionary lookup and a function call.
- Microseconds, about a thousand times slower: hashing 1 KiB with SHA-256, reading one SQLite row by its primary key, and writing 4 KiB into the operating system's cache.
- Milliseconds, about a thousand times slower again: scanning 20,000 SQLite rows without an index, and writing 4 KiB that is flushed all the way to the drive.
- Tens to hundreds of milliseconds, ten to a hundred times slower still: network round trips between cities and continents, whose floor is set by the speed of light.
Read the ladder by its rungs, not by its details. Once you know that a key lookup in memory is nanoseconds, a durable write to a drive is up to milliseconds and a cross-continent round trip is tens to hundreds of milliseconds, you can tell at a glance which part of a design dominates its latency.
Key idea
Add up a request’s latency rung by rung: the slowest rung on its path decides the total, and work on a faster rung barely shows.
Checkpoint
Check: The rungs of latency
Measure work in a process with the fastest of several repeats
Python’s timeit module runs a statement many times in a loop and reports the total. Its documentation recommends
looking at the fastest of several repeats, because slower repeats are usually caused by other programs competing
for the machine rather than by the code itself, and it switches off garbage collection while it times
(Python documentation). This script times five everyday
operations that way and prints the fastest repeat per operation:
# Time a few everyday operations with timeit and report the fastest of five repeats, per operation.
import hashlib
import json
import timeit
def show(seconds):
"""A duration in the unit that suits it."""
if seconds < 1e-6:
return f"{seconds * 1e9:.0f} ns"
if seconds < 1e-3:
return f"{seconds * 1e6:.1f} µs"
return f"{seconds * 1e3:.2f} ms"
def noop():
return None
names = {
"table": {n: n * 2 for n in range(1_000)},
"noop": noop,
"sha256": hashlib.sha256,
"kilobyte": bytes(range(256)) * 4,
"loads": json.loads,
"document": json.dumps({"id": 42, "name": "Asha", "tags": ["a", "b", "c"], "scores": list(range(100))}),
"numbers": list(range(1_000, 0, -1)),
}
CASES = [
("dict lookup, key present", "table[500]", 200_000),
("call a function that does nothing", "noop()", 200_000),
("SHA-256 of 1 KiB", "sha256(kilobyte).digest()", 5_000),
(f"json.loads of a {len(names['document'])}-byte document", "loads(document)", 2_000),
("sort 1,000 integers", "sorted(numbers)", 1_000),
]
for label, statement, number in CASES:
best = min(timeit.repeat(statement, repeat=5, number=number, globals=names)) / number
print(f"{label:<44}{show(best):>10}") Output
dict lookup, key present 28 ns call a function that does nothing 25 ns SHA-256 of 1 KiB 1.0 µs json.loads of a 453-byte document 11.6 µs sort 1,000 integers 5.0 µs
This output changes from run to run: Timings change on every run and on every computer; the values shown come from one run on the computer named below.
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bench_python.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Version note
The Run button uses Pyodide 314.0.7, a WebAssembly build of CPython 3.14.2, so in your browser the same operations usually take longer than in the native CPython above, and they depend on your device. That is the lesson of this page in one example: a latency number belongs to the machine and the runtime that produced it.
In the recorded run, a dictionary lookup and a function call took tens of nanoseconds, hashing a kilobyte about a microsecond, and parsing a small JSON document or sorting a thousand numbers between a few and about ten microseconds. Run it twice and the values move, sometimes by a factor of two or more, because the operating system decides which core runs the program and other programs compete for it. The order of magnitude stays put, and that is the part an estimate uses.
Time it in your browser
Press Run and compare your device’s numbers with the recorded ones. The values will differ, often by several times, while each operation stays on its rung.
Checkpoint
Check: Measuring work inside a process
The access path, not the database, sets a read’s latency
The same small table can answer a query in a microsecond or in a millisecond, depending on whether the database can
go straight to the row. SQLite finds a row by its primary key with a binary search, at a cost that grows with the
logarithm of the number of rows; a query on a column without an index makes it read every row, a
full table scan: A query plan that reads every row of a table to find the ones it wants, because no index leads to them. Its cost grows in step with the number of rows. (SQLite query planner).
EXPLAIN QUERY PLAN shows which one it chose:
# Point reads and scans in an in-memory SQLite table of 20,000 rows, with the plan SQLite chose for each.
import sqlite3
import timeit
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, name TEXT)")
db.executemany(
"INSERT INTO users VALUES (?, ?, ?)",
((i, f"user{i}@example.com", f"User {i}") for i in range(1, 20_001)),
)
QUERIES = [
("by primary key", "SELECT name FROM users WHERE id = ?", (12_345,)),
("by email, no index", "SELECT name FROM users WHERE email = ?", ("user12345@example.com",)),
]
def report(label, sql, args):
plan = db.execute("EXPLAIN QUERY PLAN " + sql, args).fetchall()[0][3]
run = lambda: db.execute(sql, args).fetchone()
number = 2_000 if "SCAN" not in plan else 20
best = min(timeit.repeat(run, repeat=5, number=number)) / number
shown = f"{best * 1e6:.1f} µs" if best < 1e-3 else f"{best * 1e3:.2f} ms"
print(f"{label:<22}{shown:>10} plan: {plan}")
return best
key = report(*QUERIES[0])
scan = report(*QUERIES[1])
db.execute("CREATE INDEX users_email ON users (email)")
indexed = report("by email, with index", QUERIES[1][1], QUERIES[1][2])
print(f"The scan took {scan / key:,.0f} times as long as the primary-key read; the index made it {scan / indexed:,.0f} times faster.") Output
by primary key 1.3 µs plan: SEARCH users USING INTEGER PRIMARY KEY (rowid=?) by email, no index 790.6 µs plan: SCAN users by email, with index 1.7 µs plan: SEARCH users USING INDEX users_email (email=?) The scan took 597 times as long as the primary-key read; the index made it 476 times faster.
This output changes from run to run: Timings change on every run and on every computer.
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bench_sqlite.py
The table is in memory, so no disk is involved: the difference of several hundred times comes only from how much
work each query does. A plan that says SCAN on a large table is a warning sign in any design review, and it grows
with the table, while the indexed read barely changes. The database is the same; the access path decides its
latency.
The chart counts that work as the table grows, for a scan that checks every value and a binary search that halves the range at each probe. Press Play to double the table step by step, and stop at the 20,000 rows of the example:
- Linear search, measured (circles)
- Binary search, measured (squares)
- Derived count (dashed): n for linear search; ⌊log₂ n⌋ + 1 for binary search
- The size in focus (ringed)
n = 1: linear search checks 1 value and binary search makes 1 probe. The dashed lines are the derived counts: n and ⌊log₂ n⌋ + 1.
From n = 1 to 2,000,000, searching for a value larger than every one, the counts grew: linear search from 1 to 2,000,000 values checked and binary search from 1 to 21 probes. Each matched the derived count at every size: n for linear search and ⌊log₂ n⌋ + 1 for binary search.
Every measured count as a table
| n | Linear search: values checked | Binary search: probes |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 4 | 4 | 3 |
| 8 | 8 | 4 |
| 16 | 16 | 5 |
| 32 | 32 | 6 |
| 64 | 64 | 7 |
| 128 | 128 | 8 |
| 256 | 256 | 9 |
| 512 | 512 | 10 |
| 1,024 | 1,024 | 11 |
| 2,048 | 2,048 | 12 |
| 4,096 | 4,096 | 13 |
| 8,192 | 8,192 | 14 |
| 16,384 | 16,384 | 15 |
| 20,000 | 20,000 | 15 |
| 32,768 | 32,768 | 16 |
| 65,536 | 65,536 | 17 |
| 131,072 | 131,072 | 18 |
| 262,144 | 262,144 | 19 |
| 524,288 | 524,288 | 20 |
| 1,048,576 | 1,048,576 | 21 |
| 2,000,000 | 2,000,000 | 21 |
At 20,000 rows the scan checks 20,000 values and the search makes 15 probes; at 2,000,000 rows the scan checks a hundred times more and the search makes 21. The measured gap in the example is smaller than the ratio of the counts, because a step of the scan and a probe of the search do different amounts of work, but the shape is the one to design for: the scan grows with the table and the search barely moves.
Checkpoint
Check: The access path of a read
A durable write waits for the drive
Writing to a file usually only copies the bytes into the operating system’s cache, which is fast. Making the write
durable means waiting until it is safe on the drive, and what “safe” means depends on the system. On macOS,
fsync() moves the data to the drive, but the drive may keep it in its own cache and write it later; the
F_FULLFSYNC control asks the drive to write everything it has buffered to permanent storage
(Apple fsync manual).
Step through one write made each of the three ways, and see where the data is when the program is told it is done:
The drawing shows the whole scene; its 11 steps are listed below.
Every step as text
- A plain write. write() hands the 4 KiB to the operating system, which copies it into its file cache in memory.
- Done in microseconds. The call returns at once. Nothing has reached the drive yet, so a crash now loses the data. In the recorded run this took microseconds.
- Write, then fsync(). The second way writes the same 4 KiB and then calls fsync(). The operating system sends the bytes to the drive and waits for it to accept them.
- To the drive. The drive takes the 4 KiB into its own cache. Apple's manual warns that the drive may write the data to permanent storage much later, and in another order.
- The drive accepts. The drive answers as soon as the data is in its cache.
- Done in a tenth of a ms. fsync() returns after about a tenth of a millisecond in the recorded run. A power cut now can still lose what sits in the drive's cache.
- Write, then F_FULLFSYNC. The third way asks for F_FULLFSYNC after the write, which tells the drive to move everything it has buffered to permanent storage before it answers.
- Flush everything. The operating system passes the request on to the drive.
- Onto the flash. The drive writes its cache to its flash cells. This is the step that a crash or a power cut cannot undo.
- On permanent storage. Only now does the drive answer, after milliseconds in the recorded run, tens of times longer than fsync().
- Durable, and the slowest. The program is told the write is done. Waiting for one such flush per request, one request at a time, allows only a few hundred durable writes a second.
A durable write: A write that has reached storage that keeps it through a crash or a power cut, not only a cache in memory. A program that waits for one pays the drive's flush time. is the third kind, and only the third. This script times 4 KiB writes all three ways:
# Write 4 KiB blocks to a file 200 times each way and time every write: into the operating system's
# cache only, then also waiting for fsync(), then (on macOS) for F_FULLFSYNC, which also empties the drive's cache.
import os
import time
BLOCK = b"x" * 4096
WRITES = 200
def show(ns):
return f"{ns / 1000:.1f} µs" if ns < 1_000_000 else f"{ns / 1_000_000:.1f} ms"
def measure(flush):
times = []
with open("blocks.bin", "wb") as f:
for _ in range(WRITES):
start = time.perf_counter_ns()
f.write(BLOCK)
f.flush()
flush(f.fileno())
times.append(time.perf_counter_ns() - start)
os.remove("blocks.bin")
times.sort()
return times[len(times) // 2], times[int(len(times) * 0.99)]
ways = [("write, OS cache only", lambda fd: None), ("write + fsync()", os.fsync)]
try:
import fcntl
if hasattr(fcntl, "F_FULLFSYNC"):
ways.append(("write + F_FULLFSYNC", lambda fd: fcntl.fcntl(fd, fcntl.F_FULLFSYNC)))
except ImportError:
pass
print(f"{WRITES} writes of 4 KiB each {'median':>9} {'p99':>9} writes/s, one at a time")
for name, flush in ways:
median, p99 = measure(flush)
print(f"{name:<26}{show(median):>9} {show(p99):>9} {1e9 / median:>10,.0f}") Output
200 writes of 4 KiB each median p99 writes/s, one at a time write, OS cache only 10.1 µs 103.6 µs 99,167 write + fsync() 122.7 µs 455.5 µs 8,152 write + F_FULLFSYNC 4.2 ms 22.1 ms 240
This output changes from run to run: Timings change on every run and on every computer, and the F_FULLFSYNC line appears only on macOS.
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bench_disk.py
On the machine that recorded this output, a Mac with Apple silicon writing to its internal SSD, a full flush took
tens of times longer than fsync() and hundreds of times longer than a cached write. The last column is the
consequence for a design: a system that waits for one full flush per request, one request at a time, can only make
a few hundred durable writes a second on this drive. Databases care about exactly this. PostgreSQL’s documentation
warns that many SSDs have volatile write-back caches, and that on macOS write caching can be prevented by setting
wal_sync_method to fsync_writethrough
(PostgreSQL WAL reliability). Its
group commit: Making several transactions durable with a single flush to storage, so that the commits a second are no longer capped at one flush per commit. makes several transactions durable with a single flush to raise throughput
(commit_delay).
Test on the system you will run
The same fsync() call promises different things on different operating systems and file systems, so a durable
write measured on a laptop says little about a server. Measure on the machine type, operating system and storage
you will deploy to, and state all three next to the number.
Checkpoint
Check: What a durable write waits for
Distance sets a floor that no hardware can lower
The speed of light in a vacuum is exactly 299,792,458 metres a second (NIST), and in optical fibre light travels at roughly two thirds of that speed (Singla and others), about 200 km per millisecond. A round trip covers the distance twice, so every 1,000 km between client and server adds at least 10 ms. This program computes the floor for a few routes from their great-circle distance: The shortest distance between two points along the surface of a sphere, measured on the circle whose centre is the sphere's centre. Real cables run longer., using the Earth’s mean radius from the WGS 84 standard (NGA) and city coordinates from GeoNames, in 14 languages:
Python 3.14 · main.py
from math import asin, cos, radians, sin, sqrt
from typing import NamedTuple
# Light in a vacuum (exact) and in fibre (about two thirds as fast).
VACUUM_KM_PER_S = 299_792.458
FIBRE_KM_PER_S = VACUUM_KM_PER_S * 2 / 3
EARTH_RADIUS_KM = 6_371.0087714 # the WGS 84 mean radius
class City(NamedTuple):
name: str
lat: float # degrees north and east (GeoNames)
lon: float
MUMBAI = City("Mumbai", 19.0728, 72.8826)
DELHI = City("Delhi", 28.6519, 77.2315)
LONDON = City("London", 51.5085, -0.1257)
NEW_YORK = City("New York", 40.7143, -74.0060)
ROUTES = [(MUMBAI, DELHI), (MUMBAI, LONDON), (MUMBAI, NEW_YORK), (LONDON, NEW_YORK)]
def hav(angle: float) -> float:
return sin(angle / 2) ** 2
def great_circle_km(a: City, b: City) -> float:
"""The haversine formula on a sphere."""
lat1, lon1, lat2, lon2 = map(radians, (a.lat, a.lon, b.lat, b.lon))
h = hav(lat2 - lat1) + cos(lat1) * cos(lat2) * hav(lon2 - lon1)
return 2 * EARTH_RADIUS_KM * asin(sqrt(h))
def round_trip_ms(km: float, km_per_s: float) -> float:
return 2 * km / km_per_s * 1000
print(f"{'Route':<20}{'distance':>10}{'vacuum':>9}{'fibre':>9}")
for a, b in ROUTES:
km = great_circle_km(a, b)
vacuum = round_trip_ms(km, VACUUM_KM_PER_S)
fibre = round_trip_ms(km, FIBRE_KM_PER_S)
print(
f"{a.name + ' - ' + b.name:<20}{km:>7.0f} km{vacuum:>6.0f} ms{fibre:>6.0f} ms"
) In Python: map(radians, …) turns all four angles into radians in one line, and a format spec such as :>7.0f rounds to a whole number and pads it to seven characters at once.
Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py
JavaScript Node 24 · main.mjs
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
const VACUUM_KM_PER_S = 299_792.458;
const FIBRE_KM_PER_S = (VACUUM_KM_PER_S * 2) / 3;
const EARTH_RADIUS_KM = 6_371.0087714; // the WGS 84 mean radius
// Latitude and longitude in degrees north and east (GeoNames).
const MUMBAI = { name: "Mumbai", lat: 19.0728, lon: 72.8826 };
const DELHI = { name: "Delhi", lat: 28.6519, lon: 77.2315 };
const LONDON = { name: "London", lat: 51.5085, lon: -0.1257 };
const NEW_YORK = { name: "New York", lat: 40.7143, lon: -74.006 };
const ROUTES = [
[MUMBAI, DELHI],
[MUMBAI, LONDON],
[MUMBAI, NEW_YORK],
[LONDON, NEW_YORK],
];
const radians = (degrees) => (degrees * Math.PI) / 180;
const hav = (angle) => Math.sin(angle / 2) ** 2;
// The haversine formula on a sphere.
function greatCircleKm(a, b) {
const [lat1, lon1, lat2, lon2] = [a.lat, a.lon, b.lat, b.lon].map(radians);
const h = hav(lat2 - lat1) + Math.cos(lat1) * Math.cos(lat2) * hav(lon2 - lon1);
return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(h));
}
const roundTripMs = (km, kmPerS) => ((2 * km) / kmPerS) * 1000;
const whole = (x, width) => x.toFixed(0).padStart(width);
console.log(
"Route".padEnd(20) + "distance".padStart(10) + "vacuum".padStart(9) + "fibre".padStart(9),
);
for (const [a, b] of ROUTES) {
const km = greatCircleKm(a, b);
const vacuum = whole(roundTripMs(km, VACUUM_KM_PER_S), 6);
const fibre = whole(roundTripMs(km, FIBRE_KM_PER_S), 6);
console.log(`${`${a.name} - ${b.name}`.padEnd(20)}${whole(km, 7)} km${vacuum} ms${fibre} ms`);
} In JavaScript: Math has no radians function, so radians multiplies by Math.PI / 180; toFixed(0) rounds to a whole number and padStart lines the columns up.
Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs
Java 25 LTS · Main.java
import java.util.Locale;
public class Main {
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
static final double VACUUM_KM_PER_S = 299_792.458;
static final double FIBRE_KM_PER_S = VACUUM_KM_PER_S * 2 / 3;
static final double EARTH_RADIUS_KM = 6_371.0087714; // the WGS 84 mean radius
/** Latitude and longitude in degrees north and east (GeoNames). */
record City(String name, double lat, double lon) {}
static final City MUMBAI = new City("Mumbai", 19.0728, 72.8826);
static final City DELHI = new City("Delhi", 28.6519, 77.2315);
static final City LONDON = new City("London", 51.5085, -0.1257);
static final City NEW_YORK = new City("New York", 40.7143, -74.0060);
static double hav(double angle) {
return Math.pow(Math.sin(angle / 2), 2);
}
/** The haversine formula on a sphere. */
static double greatCircleKm(City a, City b) {
double lat1 = Math.toRadians(a.lat());
double lat2 = Math.toRadians(b.lat());
double dLon = Math.toRadians(b.lon()) - Math.toRadians(a.lon());
double h = hav(lat2 - lat1) + Math.cos(lat1) * Math.cos(lat2) * hav(dLon);
return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(h));
}
static double roundTripMs(double km, double kmPerS) {
return 2 * km / kmPerS * 1000;
}
public static void main(String[] args) {
Locale.setDefault(Locale.ROOT);
City[][] routes = {{MUMBAI, DELHI}, {MUMBAI, LONDON}, {MUMBAI, NEW_YORK}, {LONDON, NEW_YORK}};
System.out.printf("%-20s%10s%9s%9s%n", "Route", "distance", "vacuum", "fibre");
for (City[] route : routes) {
double km = greatCircleKm(route[0], route[1]);
System.out.printf(
"%-20s%7.0f km%6.0f ms%6.0f ms%n",
route[0].name() + " - " + route[1].name(),
km,
roundTripMs(km, VACUUM_KM_PER_S),
roundTripMs(km, FIBRE_KM_PER_S));
}
}
} In Java: Math.toRadians converts the angles. printf rounds half up and pads, and main sets Locale.ROOT first so that no locale can change the digits.
Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java
C++23 · main.cpp
#include <array>
#include <cmath>
#include <format>
#include <numbers>
#include <print>
#include <string_view>
#include <utility>
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
constexpr double vacuum_km_per_s = 299'792.458;
constexpr double fibre_km_per_s = vacuum_km_per_s * 2 / 3;
constexpr double earth_radius_km = 6'371.0087714; // the WGS 84 mean radius
struct City {
std::string_view name;
double lat; // degrees north and east (GeoNames)
double lon;
};
constexpr City mumbai{"Mumbai", 19.0728, 72.8826};
constexpr City delhi{"Delhi", 28.6519, 77.2315};
constexpr City london{"London", 51.5085, -0.1257};
constexpr City new_york{"New York", 40.7143, -74.0060};
double radians(double degrees) { return degrees * std::numbers::pi / 180; }
double hav(double angle) { return std::pow(std::sin(angle / 2), 2); }
// The haversine formula on a sphere.
double great_circle_km(const City &a, const City &b) {
const double lat1 = radians(a.lat), lat2 = radians(b.lat);
const double h = hav(lat2 - lat1) + std::cos(lat1) * std::cos(lat2) *
hav(radians(b.lon) - radians(a.lon));
return 2 * earth_radius_km * std::asin(std::sqrt(h));
}
double round_trip_ms(double km, double km_per_s) {
return 2 * km / km_per_s * 1000;
}
int main() {
constexpr std::array<std::pair<City, City>, 4> routes{{{mumbai, delhi},
{mumbai, london},
{mumbai, new_york},
{london, new_york}}};
std::println("{:<20}{:>10}{:>9}{:>9}", "Route", "distance", "vacuum",
"fibre");
for (const auto &[a, b] : routes) {
const double km = great_circle_km(a, b);
std::println("{:<20}{:>7.0f} km{:>6.0f} ms{:>6.0f} ms",
std::format("{} - {}", a.name, b.name), km,
round_trip_ms(km, vacuum_km_per_s),
round_trip_ms(km, fibre_km_per_s));
}
} In C++: std::numbers::pi, new in C++20, gives π, and std::println pads and rounds with the same format specs as Python's f-strings.
Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
City mumbai = new("Mumbai", 19.0728, 72.8826);
City delhi = new("Delhi", 28.6519, 77.2315);
City london = new("London", 51.5085, -0.1257);
City newYork = new("New York", 40.7143, -74.0060);
(City From, City To)[] routes =
[
(mumbai, delhi),
(mumbai, london),
(mumbai, newYork),
(london, newYork),
];
Console.WriteLine($"{"Route",-20}{"distance",10}{"vacuum",9}{"fibre",9}");
foreach (var (from, to) in routes)
{
double km = Geo.GreatCircleKm(from, to);
double vacuum = Geo.RoundTripMs(km, Geo.VacuumKmPerS);
double fibre = Geo.RoundTripMs(km, Geo.FibreKmPerS);
string route = $"{from.Name} - {to.Name}";
Console.WriteLine($"{route,-20}{km,7:F0} km{vacuum,6:F0} ms{fibre,6:F0} ms");
}
// Latitude and longitude in degrees north and east (GeoNames).
record City(string Name, double Lat, double Lon);
static class Geo
{
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
public const double VacuumKmPerS = 299_792.458;
public const double FibreKmPerS = VacuumKmPerS * 2 / 3;
const double EarthRadiusKm = 6_371.0087714; // the WGS 84 mean radius
static double Hav(double angle) => Math.Pow(Math.Sin(angle / 2), 2);
// The haversine formula on a sphere.
public static double GreatCircleKm(City a, City b)
{
double lat1 = double.DegreesToRadians(a.Lat), lat2 = double.DegreesToRadians(b.Lat);
double dLon = double.DegreesToRadians(b.Lon) - double.DegreesToRadians(a.Lon);
double h = Hav(lat2 - lat1) + Math.Cos(lat1) * Math.Cos(lat2) * Hav(dLon);
return 2 * EarthRadiusKm * Math.Asin(Math.Sqrt(h));
}
public static double RoundTripMs(double km, double kmPerS) => 2 * km / kmPerS * 1000;
} In C#: double.DegreesToRadians converts the angles, and {km,7:F0} rounds to a whole number and pads it to seven characters inside the interpolated string.
Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs
C23 · main.c
#include <math.h>
#include <stddef.h>
#include <stdio.h>
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
constexpr double vacuum_km_per_s = 299792.458;
constexpr double fibre_km_per_s = vacuum_km_per_s * 2 / 3;
constexpr double earth_radius_km = 6371.0087714; // the WGS 84 mean radius
constexpr double pi = 3.14159265358979323846;
typedef struct {
const char *name;
double lat; // degrees north and east (GeoNames)
double lon;
} City;
static const City mumbai = {"Mumbai", 19.0728, 72.8826};
static const City delhi = {"Delhi", 28.6519, 77.2315};
static const City london = {"London", 51.5085, -0.1257};
static const City new_york = {"New York", 40.7143, -74.0060};
static double radians(double degrees) { return degrees * pi / 180; }
static double hav(double angle) { return pow(sin(angle / 2), 2); }
// The haversine formula on a sphere.
static double great_circle_km(const City *a, const City *b) {
const double lat1 = radians(a->lat), lat2 = radians(b->lat);
const double h =
hav(lat2 - lat1) +
cos(lat1) * cos(lat2) * hav(radians(b->lon) - radians(a->lon));
return 2 * earth_radius_km * asin(sqrt(h));
}
static double round_trip_ms(double km, double km_per_s) {
return 2 * km / km_per_s * 1000;
}
int main(void) {
static const City *const routes[][2] = {{&mumbai, &delhi},
{&mumbai, &london},
{&mumbai, &new_york},
{&london, &new_york}};
printf("%-20s%10s%9s%9s\n", "Route", "distance", "vacuum", "fibre");
for (size_t i = 0; i < sizeof routes / sizeof routes[0]; i++) {
const City *a = routes[i][0], *b = routes[i][1];
const double km = great_circle_km(a, b);
char route[32];
snprintf(route, sizeof route, "%s - %s", a->name, b->name);
printf("%-20s%7.0f km%6.0f ms%6.0f ms\n", route, km,
round_trip_ms(km, vacuum_km_per_s),
round_trip_ms(km, fibre_km_per_s));
}
return 0;
} In C: The C standard has no constant for π (M_PI comes from POSIX), so the program defines pi; C23's constexpr lets one constant be computed from another at compile time.
Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main
PHP 8.5 · main.php
<?php
declare(strict_types=1);
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
const VACUUM_KM_PER_S = 299_792.458;
const FIBRE_KM_PER_S = VACUUM_KM_PER_S * 2 / 3;
const EARTH_RADIUS_KM = 6_371.0087714; // the WGS 84 mean radius
final readonly class City
{
public function __construct(
public string $name,
public float $lat, // degrees north and east (GeoNames)
public float $lon,
) {}
}
function hav(float $angle): float
{
return sin($angle / 2) ** 2;
}
// The haversine formula on a sphere.
function greatCircleKm(City $a, City $b): float
{
[$lat1, $lon1, $lat2, $lon2] = array_map(deg2rad(...), [$a->lat, $a->lon, $b->lat, $b->lon]);
$h = hav($lat2 - $lat1) + cos($lat1) * cos($lat2) * hav($lon2 - $lon1);
return 2 * EARTH_RADIUS_KM * asin(sqrt($h));
}
function roundTripMs(float $km, float $kmPerS): float
{
return 2 * $km / $kmPerS * 1000;
}
$mumbai = new City('Mumbai', 19.0728, 72.8826);
$delhi = new City('Delhi', 28.6519, 77.2315);
$london = new City('London', 51.5085, -0.1257);
$newYork = new City('New York', 40.7143, -74.0060);
$routes = [[$mumbai, $delhi], [$mumbai, $london], [$mumbai, $newYork], [$london, $newYork]];
printf("%-20s%10s%9s%9s\n", 'Route', 'distance', 'vacuum', 'fibre');
foreach ($routes as [$a, $b]) {
$km = greatCircleKm($a, $b);
$vacuum = roundTripMs($km, VACUUM_KM_PER_S);
$fibre = roundTripMs($km, FIBRE_KM_PER_S);
printf("%-20s%7.0f km%6.0f ms%6.0f ms\n", "{$a->name} - {$b->name}", $km, $vacuum, $fibre);
} In PHP: deg2rad(...) is passed to array_map as a first-class callable, and printf pads and rounds the way C's printf does.
Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php
Rust 1.99 · main.rs
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
const VACUUM_KM_PER_S: f64 = 299_792.458;
const FIBRE_KM_PER_S: f64 = VACUUM_KM_PER_S * 2.0 / 3.0;
const EARTH_RADIUS_KM: f64 = 6_371.008_771_4; // the WGS 84 mean radius
struct City {
name: &'static str,
lat: f64, // degrees north and east (GeoNames)
lon: f64,
}
impl City {
const fn new(name: &'static str, lat: f64, lon: f64) -> Self {
Self { name, lat, lon }
}
}
const MUMBAI: City = City::new("Mumbai", 19.0728, 72.8826);
const DELHI: City = City::new("Delhi", 28.6519, 77.2315);
const LONDON: City = City::new("London", 51.5085, -0.1257);
const NEW_YORK: City = City::new("New York", 40.7143, -74.0060);
fn hav(angle: f64) -> f64 {
(angle / 2.0).sin().powi(2)
}
/// The haversine formula on a sphere.
fn great_circle_km(a: &City, b: &City) -> f64 {
let (lat1, lat2) = (a.lat.to_radians(), b.lat.to_radians());
let d_lon = b.lon.to_radians() - a.lon.to_radians();
let h = hav(lat2 - lat1) + lat1.cos() * lat2.cos() * hav(d_lon);
2.0 * EARTH_RADIUS_KM * h.sqrt().asin()
}
fn round_trip_ms(km: f64, km_per_s: f64) -> f64 {
2.0 * km / km_per_s * 1000.0
}
fn main() {
let routes = [
(&MUMBAI, &DELHI),
(&MUMBAI, &LONDON),
(&MUMBAI, &NEW_YORK),
(&LONDON, &NEW_YORK),
];
println!(
"{:<20}{:>10}{:>9}{:>9}",
"Route", "distance", "vacuum", "fibre"
);
for (a, b) in routes {
let km = great_circle_km(a, b);
let vacuum = round_trip_ms(km, VACUUM_KM_PER_S);
let fibre = round_trip_ms(km, FIBRE_KM_PER_S);
let route = format!("{} - {}", a.name, b.name);
println!("{route:<20}{km:>7.0} km{vacuum:>6.0} ms{fibre:>6.0} ms");
}
} In Rust: f64 has to_radians, sin, cos, asin and sqrt as methods, so the last step reads left to right as h.sqrt().asin(); a const fn builds each city at compile time.
Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main
TypeScript 6.0 · main.ts
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
const VACUUM_KM_PER_S = 299_792.458;
const FIBRE_KM_PER_S = (VACUUM_KM_PER_S * 2) / 3;
const EARTH_RADIUS_KM = 6_371.0087714; // the WGS 84 mean radius
interface City {
readonly name: string;
readonly lat: number; // degrees north and east (GeoNames)
readonly lon: number;
}
const MUMBAI: City = { name: "Mumbai", lat: 19.0728, lon: 72.8826 };
const DELHI: City = { name: "Delhi", lat: 28.6519, lon: 77.2315 };
const LONDON: City = { name: "London", lat: 51.5085, lon: -0.1257 };
const NEW_YORK: City = { name: "New York", lat: 40.7143, lon: -74.006 };
const ROUTES: readonly (readonly [City, City])[] = [
[MUMBAI, DELHI],
[MUMBAI, LONDON],
[MUMBAI, NEW_YORK],
[LONDON, NEW_YORK],
];
const radians = (degrees: number): number => (degrees * Math.PI) / 180;
const hav = (angle: number): number => Math.sin(angle / 2) ** 2;
// The haversine formula on a sphere.
function greatCircleKm(a: City, b: City): number {
const [lat1, lon1, lat2, lon2] = [a.lat, a.lon, b.lat, b.lon].map(radians);
const h = hav(lat2 - lat1) + Math.cos(lat1) * Math.cos(lat2) * hav(lon2 - lon1);
return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(h));
}
const roundTripMs = (km: number, kmPerS: number): number => ((2 * km) / kmPerS) * 1000;
const whole = (x: number, width: number): string => x.toFixed(0).padStart(width);
console.log(
"Route".padEnd(20) + "distance".padStart(10) + "vacuum".padStart(9) + "fibre".padStart(9),
);
for (const [a, b] of ROUTES) {
const km = greatCircleKm(a, b);
const vacuum = whole(roundTripMs(km, VACUUM_KM_PER_S), 6);
const fibre = whole(roundTripMs(km, FIBRE_KM_PER_S), 6);
console.log(`${`${a.name} - ${b.name}`.padEnd(20)}${whole(km, 7)} km${vacuum} ms${fibre} ms`);
} In TypeScript: City is an interface, so the cities are plain objects that the compiler checks; the arithmetic is JavaScript's, on the same doubles.
Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts
Go 1.27 · main.go
package main
import (
"fmt"
"math"
)
const (
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
vacuumKmPerS = 299_792.458
fibreKmPerS = vacuumKmPerS * 2 / 3
earthRadiusKm = 6_371.0087714 // the WGS 84 mean radius
)
type city struct {
name string
lat, lon float64 // degrees north and east (GeoNames)
}
var (
mumbai = city{"Mumbai", 19.0728, 72.8826}
delhi = city{"Delhi", 28.6519, 77.2315}
london = city{"London", 51.5085, -0.1257}
newYork = city{"New York", 40.7143, -74.0060}
)
func radians(degrees float64) float64 { return degrees * math.Pi / 180 }
func hav(angle float64) float64 { return math.Pow(math.Sin(angle/2), 2) }
// greatCircleKm applies the haversine formula on a sphere.
func greatCircleKm(a, b city) float64 {
lat1, lat2 := radians(a.lat), radians(b.lat)
h := hav(lat2-lat1) + math.Cos(lat1)*math.Cos(lat2)*hav(radians(b.lon)-radians(a.lon))
return 2 * earthRadiusKm * math.Asin(math.Sqrt(h))
}
func roundTripMs(km, kmPerS float64) float64 { return 2 * km / kmPerS * 1000 }
func main() {
routes := [][2]city{{mumbai, delhi}, {mumbai, london}, {mumbai, newYork}, {london, newYork}}
fmt.Printf("%-20s%10s%9s%9s\n", "Route", "distance", "vacuum", "fibre")
for _, r := range routes {
km := greatCircleKm(r[0], r[1])
vacuum, fibre := roundTripMs(km, vacuumKmPerS), roundTripMs(km, fibreKmPerS)
fmt.Printf("%-20s%7.0f km%6.0f ms%6.0f ms\n", r[0].name+" - "+r[1].name, km, vacuum, fibre)
}
} In Go: The math package has no radians function, so radians multiplies by math.Pi / 180. The untyped constant fibreKmPerS is computed exactly before it becomes a float64.
Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go
Swift 6.4 · main.swift
#if canImport(Darwin)
import Darwin
#elseif canImport(WASILibc)
import WASILibc
#endif
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
let vacuumKmPerS = 299_792.458
let fibreKmPerS = vacuumKmPerS * 2 / 3
let earthRadiusKm = 6_371.0087714 // the WGS 84 mean radius
struct City {
let name: String
let lat: Double // degrees north and east (GeoNames)
let lon: Double
}
let mumbai = City(name: "Mumbai", lat: 19.0728, lon: 72.8826)
let delhi = City(name: "Delhi", lat: 28.6519, lon: 77.2315)
let london = City(name: "London", lat: 51.5085, lon: -0.1257)
let newYork = City(name: "New York", lat: 40.7143, lon: -74.0060)
let routes = [(mumbai, delhi), (mumbai, london), (mumbai, newYork), (london, newYork)]
func radians(_ degrees: Double) -> Double { degrees * Double.pi / 180 }
func hav(_ angle: Double) -> Double { pow(sin(angle / 2), 2) }
/// The haversine formula on a sphere.
func greatCircleKm(from a: City, to b: City) -> Double {
let (lat1, lat2) = (radians(a.lat), radians(b.lat))
let h = hav(lat2 - lat1) + cos(lat1) * cos(lat2) * hav(radians(b.lon) - radians(a.lon))
return 2 * earthRadiusKm * asin(h.squareRoot())
}
func roundTripMs(_ km: Double, _ kmPerS: Double) -> Double { 2 * km / kmPerS * 1000 }
func pad(_ text: String, _ width: Int, left: Bool = true) -> String {
let spaces = String(repeating: " ", count: max(0, width - text.count))
return left ? spaces + text : text + spaces
}
func whole(_ value: Double, _ width: Int) -> String {
pad(String(Int64(value.rounded())), width)
}
print(pad("Route", 20, left: false) + pad("distance", 10) + pad("vacuum", 9) + pad("fibre", 9))
for (a, b) in routes {
let km = greatCircleKm(from: a, to: b)
let route = pad("\(a.name) - \(b.name)", 20, left: false)
let vacuum = whole(roundTripMs(km, vacuumKmPerS), 6)
print("\(route)\(whole(km, 7)) km\(vacuum) ms\(whole(roundTripMs(km, fibreKmPerS), 6)) ms")
} In Swift: The standard library has no sin, cos, asin or pow, so they come from the platform's C library (Darwin on macOS, WASILibc in WebAssembly), and with no String(format:) the columns are padded by hand.
Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main
Ruby 4.0 · main.rb
# frozen_string_literal: true
# Light in a vacuum (exact) and in fibre (about two thirds as fast).
VACUUM_KM_PER_S = 299_792.458
FIBRE_KM_PER_S = VACUUM_KM_PER_S * 2 / 3
EARTH_RADIUS_KM = 6_371.0087714 # the WGS 84 mean radius
# Latitude and longitude in degrees north and east (GeoNames).
City = Data.define(:name, :lat, :lon) do
def radians = [lat, lon].map { |degrees| degrees * Math::PI / 180 }
end
MUMBAI = City.new('Mumbai', 19.0728, 72.8826)
DELHI = City.new('Delhi', 28.6519, 77.2315)
LONDON = City.new('London', 51.5085, -0.1257)
NEW_YORK = City.new('New York', 40.7143, -74.0060)
ROUTES = [[MUMBAI, DELHI], [MUMBAI, LONDON], [MUMBAI, NEW_YORK], [LONDON, NEW_YORK]].freeze
def hav(angle) = Math.sin(angle / 2)**2
# The haversine formula on a sphere.
def great_circle_km(origin, destination)
lat1, lon1 = origin.radians
lat2, lon2 = destination.radians
h = hav(lat2 - lat1) + (Math.cos(lat1) * Math.cos(lat2) * hav(lon2 - lon1))
2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(h))
end
def round_trip_ms(distance_km, km_per_s) = 2 * distance_km / km_per_s * 1000
def whole(value, width) = value.round.to_s.rjust(width)
puts "#{'Route'.ljust(20)}#{'distance'.rjust(10)}#{'vacuum'.rjust(9)}#{'fibre'.rjust(9)}"
ROUTES.each do |origin, destination|
km = great_circle_km(origin, destination)
vacuum = whole(round_trip_ms(km, VACUUM_KM_PER_S), 6)
fibre = whole(round_trip_ms(km, FIBRE_KM_PER_S), 6)
route = "#{origin.name} - #{destination.name}".ljust(20)
puts "#{route}#{whole(km, 7)} km#{vacuum} ms#{fibre} ms"
end In Ruby: Data.define makes City an immutable value class with its own radians method, and round followed by rjust pads a whole number.
Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb
Kotlin 2.4 · Main.kt
import kotlin.math.PI
import kotlin.math.asin
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.roundToLong
import kotlin.math.sin
import kotlin.math.sqrt
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
const val VACUUM_KM_PER_S = 299_792.458
const val FIBRE_KM_PER_S = VACUUM_KM_PER_S * 2 / 3
const val EARTH_RADIUS_KM = 6_371.0087714 // the WGS 84 mean radius
data class City(
val name: String,
val lat: Double, // degrees north and east (GeoNames)
val lon: Double,
)
fun radians(degrees: Double) = degrees * PI / 180
fun hav(angle: Double) = sin(angle / 2).pow(2)
// The haversine formula on a sphere.
fun greatCircleKm(
a: City,
b: City,
): Double {
val (lat1, lat2) = radians(a.lat) to radians(b.lat)
val h = hav(lat2 - lat1) + cos(lat1) * cos(lat2) * hav(radians(b.lon) - radians(a.lon))
return 2 * EARTH_RADIUS_KM * asin(sqrt(h))
}
fun roundTripMs(
km: Double,
kmPerS: Double,
) = 2 * km / kmPerS * 1000
fun Double.whole(width: Int) = roundToLong().toString().padStart(width)
fun main() {
val mumbai = City("Mumbai", 19.0728, 72.8826)
val delhi = City("Delhi", 28.6519, 77.2315)
val london = City("London", 51.5085, -0.1257)
val newYork = City("New York", 40.7143, -74.0060)
val routes = listOf(mumbai to delhi, mumbai to london, mumbai to newYork, london to newYork)
val header = "Route".padEnd(20) + "distance".padStart(10) + "vacuum".padStart(9)
println(header + "fibre".padStart(9))
for ((a, b) in routes) {
val km = greatCircleKm(a, b)
val vacuum = roundTripMs(km, VACUUM_KM_PER_S).whole(6)
val fibre = roundTripMs(km, FIBRE_KM_PER_S).whole(6)
println("${"${a.name} - ${b.name}".padEnd(20)}${km.whole(7)} km$vacuum ms$fibre ms")
}
} In Kotlin: kotlin.math has sin, cos, asin, sqrt and PI on every platform, but the common standard library has no String.format, so whole numbers are padded with padStart.
Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar
Dart 3.13 · main.dart
import 'dart:math';
// Light in a vacuum (exact) and in fibre (about two thirds as fast).
const vacuumKmPerS = 299_792.458;
const fibreKmPerS = vacuumKmPerS * 2 / 3;
const earthRadiusKm = 6_371.0087714; // the WGS 84 mean radius
/// Latitude and longitude in degrees north and east (GeoNames).
typedef City = ({String name, double lat, double lon});
const City mumbai = (name: 'Mumbai', lat: 19.0728, lon: 72.8826);
const City delhi = (name: 'Delhi', lat: 28.6519, lon: 77.2315);
const City london = (name: 'London', lat: 51.5085, lon: -0.1257);
const City newYork = (name: 'New York', lat: 40.7143, lon: -74.0060);
const routes = [
(mumbai, delhi),
(mumbai, london),
(mumbai, newYork),
(london, newYork),
];
double radians(double degrees) => degrees * pi / 180;
double hav(double angle) => pow(sin(angle / 2), 2).toDouble();
/// The haversine formula on a sphere.
double greatCircleKm(City a, City b) {
final (lat1, lat2) = (radians(a.lat), radians(b.lat));
final dLon = radians(b.lon) - radians(a.lon);
final h = hav(lat2 - lat1) + cos(lat1) * cos(lat2) * hav(dLon);
return 2 * earthRadiusKm * asin(sqrt(h));
}
double roundTripMs(double km, double kmPerS) => 2 * km / kmPerS * 1000;
String whole(double value, int width) =>
value.toStringAsFixed(0).padLeft(width);
void main() {
print(
'${'Route'.padRight(20)}${'distance'.padLeft(10)}'
'${'vacuum'.padLeft(9)}${'fibre'.padLeft(9)}',
);
for (final (a, b) in routes) {
final km = greatCircleKm(a, b);
final vacuum = whole(roundTripMs(km, vacuumKmPerS), 6);
final fibre = whole(roundTripMs(km, fibreKmPerS), 6);
final route = '${a.name} - ${b.name}'.padRight(20);
print('$route${whole(km, 7)} km$vacuum ms$fibre ms');
}
} In Dart: pow from dart:math returns a num, so hav converts its result with toDouble(), and toStringAsFixed(0) rounds to a whole number.
Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart
What every language printed
Route distance vacuum fibre Mumbai - Delhi 1153 km 8 ms 12 ms Mumbai - London 7192 km 48 ms 72 ms Mumbai - New York 12538 km 84 ms 125 ms London - New York 5570 km 37 ms 56 ms
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 66 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 156 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 4 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 14 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 30 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 722 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 186 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 11 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
Real round trips are slower than these floors. Cables do not follow great circles, and every router, queue and handshake adds time: in the measurements of Singla and colleagues, the median ping was about 3.2 times the vacuum floor and fetching just the HTML of a popular page took a median of 34 times the floor. Even so, these floors are the most useful numbers on this page: nothing can beat the vacuum figure, and no route over fibre can beat the fibre figure. A user in Mumbai talking to a server in New York over fibre waits at least 125 ms for every round trip (84 ms even at the speed of light in a vacuum), so a design for that user must reduce the number of round trips or move the server closer. Here is what that means for a page that needs ten answers from New York:
The drawing shows the whole scene; its 8 steps are listed below.
Every step as text
- The floor of one call. Over fibre, light needs at least 63 ms to cover the 12,538 km to New York, so one request and its reply take at least 125 ms before the server does any work.
- Call 1. The page sends its first request and waits for the answer.
- Answer 1. The answer comes back at least 125 ms after the request left.
- Calls 2 to 10, one by one. Each further call waits for the one before it, so ten calls in a row cost ten round trips, at least 1,250 ms. No faster server can lower that, because the time is in the cables.
- In parallel instead. If the ten calls do not depend on each other, the page can send them together. They share one round trip, so the wait drops to about 125 ms.
- One batched call. A single request that asks for all ten answers costs the same one round trip, and the server can gather the answers next to its own data.
- A copy close by. A copy of the data in Delhi, 1,153 km away, has a floor of only 12 ms a round trip. Moving the data closer is the only way to lower the floor itself.
- Where the time went. The page waited at least 1,250 ms, 125 ms or 12 ms for the same ten answers. Count the round trips on a request's path and multiply by the floor before you tune anything else.
To measure real network timings yourself, curl’s --write-out option prints when each phase of a request finished
(curl manual), for example
curl -s -o /dev/null -w '%{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer}\n' https://example.com/
for the DNS lookup, the TCP connection, the TLS handshake and the first byte, in seconds from the start. Run it a
few times, and from more than one place: one measurement from one network is an anecdote.
Key idea
Every 1,000 km of distance adds at least 10 ms to a round trip over fibre, so count the round trips on a request’s path and multiply before you tune anything else.
Checkpoint
Check: The speed-of-light floor
Why copied tables mislead
Tables of “latency numbers” travel from slide to slide without the context that made them true. A well-known one, in Peter Norvig’s essay Teach Yourself Programming in Ten Years, gives approximate timings for “a typical PC” of its time, including 8 ms for a disk seek. That figure describes a spinning disk moving its head to a new place; an SSD has no head to move, and the drive measured above finished a cached write in microseconds and even a fully flushed one in a few milliseconds. Its 150 ms for a packet from the US to Europe and back is a different kind of number: distance sets a floor under it that no new hardware moves (37 ms in a vacuum and 56 ms over fibre between London and New York, from the program above), so it remains the right order of magnitude.
| The copied figure | What sets it | On this page |
|---|---|---|
| A disk seek, 8 ms | A spinning disk’s head, which an SSD does not have | A cached 4 KiB write in microseconds, a full flush in milliseconds |
| US to Europe and back, 150 ms | The distance, which no hardware moves | London to New York at least 37 ms in a vacuum, 56 ms over fibre |
So treat any latency number as a measurement that needs its context:
- Hardware and software. The machine, the drive, the operating system and the runtime. The same Python code ran at different speeds natively and in the browser above.
- The exact operation. “A write” can mean into a cache, to the drive, or to permanent storage, and those differed by hundreds of times above.
- The statistic. The fastest of several runs, the median and the 99th percentile answer different questions. The disk example prints both a median and a p99 (99th percentile): The latency within which 99 % of requests finish, so the slowest 1 % take longer. Tail latency is read from such high percentiles, because an average hides the slowest requests. More in “Latency, throughput and percentiles”, and the p99 is much higher.
- When and how it was measured. Hardware changes; a script that anyone can run again keeps a number honest.
Checkpoint
Check: A latency number and its context
Practise: compute the floor of a round trip
Write the two functions behind the floors on this page: the great-circle distance between two points with the haversine formula, and the fastest round trip over fibre for a distance. Its sample tests, from a quarter of the equator to London and New York, run here on the page:
Exercise · Medium · Python
Compute the speed-of-light floor of a round trip
No network can beat the speed of light, so the shortest possible round trip between two places is a useful floor for any latency estimate. Write two functions in floor.py.
great_circle_km(lat1, lon1, lat2, lon2) returns the distance in kilometres along the Earth's surface between two points given in degrees, with the haversine formula on a sphere of radius EARTH_RADIUS_KM:
- Convert all four angles to radians with
math.radians. - Compute
h = sin(Δlat / 2)² + cos(lat1) · cos(lat2) · sin(Δlon / 2)². - The distance is
2 · R · asin(√h).
fibre_rtt_ms(distance_km) returns the shortest round trip in milliseconds over optical fibre, where light travels at FIBRE_KM_PER_S, about two thirds of its speed in a vacuum: there and back is twice the distance.
The sample tests check a few points whose distances you can work out by hand, such as a quarter of the way round the equator, and a real pair of cities.
Starter code · floor.py
import math
EARTH_RADIUS_KM = 6_371.0
FIBRE_KM_PER_S = 299_792.458 * 2 / 3
def great_circle_km(lat1, lon1, lat2, lon2):
"""Distance in km along the Earth's surface between two points given in degrees (haversine formula)."""
# Replace this line with your code.
return 0.0
def fibre_rtt_ms(distance_km):
"""The fastest possible round trip in milliseconds over fibre for a one-way distance in km."""
# Replace this line with your code.
return 0.0 The sample tests · test_floor.py
import math
from floor import EARTH_RADIUS_KM, fibre_rtt_ms, great_circle_km
def test_same_point():
"""is zero from a point to itself"""
assert great_circle_km(19.07, 72.88, 19.07, 72.88) == 0
def test_quarter_of_the_equator():
"""measures a quarter of the way round the equator"""
expected = math.pi / 2 * EARTH_RADIUS_KM
assert math.isclose(great_circle_km(0, 0, 0, 90), expected, rel_tol=1e-9)
def test_pole_to_pole():
"""measures half the way round, from pole to pole"""
assert math.isclose(great_circle_km(90, 0, -90, 0), math.pi * EARTH_RADIUS_KM, rel_tol=1e-9)
def test_real_cities():
"""measures London to New York at about 5,570 km"""
assert math.isclose(great_circle_km(51.5085, -0.1257, 40.7143, -74.0060), 5_570, rel_tol=0.005)
def test_round_trip():
"""turns a one-way distance into a round trip over fibre"""
assert fibre_rtt_ms(0) == 0
assert math.isclose(fibre_rtt_ms(1_000), 10.0069, rel_tol=1e-4)
assert math.isclose(fibre_rtt_ms(5_570), 55.74, rel_tol=1e-3) A hint
Work in radians from the start: lat1, lon1, lat2, lon2 = map(math.radians, (lat1, lon1, lat2, lon2)). Then Δlat is lat2 - lat1 and Δlon is lon2 - lon1. For the round trip, time is distance divided by speed, so 2 * distance_km / FIBRE_KM_PER_S is in seconds: multiply by 1,000 for milliseconds.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Last, test what you measured and computed here. The session starts on your weakest rung and steps up a level each time you answer right:
Practice that adapts to you
Practise this lesson
13 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Warm-up (fresher to mid level): roughly how long do a lookup in memory, a durable write to an SSD and a round trip from Mumbai to New York take, and why do their orders of magnitude matter more than their exact values?
In the runs on this page a dictionary lookup took tens of nanoseconds, a 4 KiB write flushed all the way to the drive took milliseconds, and a round trip from Mumbai to New York can never take less than 125 ms over fibre. Each step is a thousand times or more, so the slowest operation on a request’s path decides its latency: ten round trips across continents, one after another, take over a second whatever the code does, while a thousand lookups in memory take microseconds. Exact values change with the hardware, the operating system, the runtime and the load, and a number copied without them can be wrong by orders of magnitude, as a spinning disk’s seek and an SSD’s write are. Estimate with the order of magnitude, then measure the parts that dominate on the machines you will run.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Mid to senior
A page served to users in Mumbai calls a service hosted in London eight times, one call after another, and must render within 400 ms. Can it ever meet the target? What would you change first?
-
Mid to senior
An order service must make each order durable before it replies, and a full flush to the database host's SSD takes about 4 ms. How many orders a second can one connection commit, and how do databases get past that limit?
Key takeaways
- Think in rungs: nanoseconds in memory, microseconds for small work and indexed reads, milliseconds for durable writes and scans, tens to hundreds of milliseconds across cities and continents.
- Measure with a documented method (
timeit, the fastest of several repeats) and publish the hardware and runtime with the number. - The access path, not the database, decides a read’s latency: a scan grows with the table, an indexed read barely does.
- Durability has a price, and its meaning differs between systems: one full flush per request caps a drive at a few hundred durable writes a second unless writes are grouped.
- Distance sets a floor of about 10 ms of round trip per 1,000 km over fibre, and real round trips are slower still: in one large study the median ping took 3.2 times the vacuum floor.
Terms in this lesson
- durable write
- A write that has reached storage that keeps it through a crash or a power cut, not only a cache in memory. A program that waits for one pays the drive's flush time.
- full table scan
- A query plan that reads every row of a table to find the ones it wants, because no index leads to them. Its cost grows in step with the number of rows.
- great-circle distance
- The shortest distance between two points along the surface of a sphere, measured on the circle whose centre is the sphere's centre. Real cables run longer.
- group commit
- Making several transactions durable with a single flush to storage, so that the commits a second are no longer capped at one flush per commit.
- order of magnitude
- A factor of ten. Two quantities are an order of magnitude apart when one is about ten times the other; a microsecond and a millisecond are three orders apart.
References
- timeit, measure execution time of small code snippets (Python Software Foundation)
- Query planning (SQLite documentation) (SQLite)
- fsync(2), the macOS manual page (Apple)
- PostgreSQL documentation: Reliability and the Write-Ahead Log (The PostgreSQL Global Development Group)
- PostgreSQL documentation: Write Ahead Log settings (commit_delay) (The PostgreSQL Global Development Group)
- CODATA value: speed of light in vacuum (National Institute of Standards and Technology (NIST))
- The Internet at the Speed of Light (ACM HotNets (Singla, Chandrasekaran, Godfrey and Maggs))
- World Geodetic System 1984: Its Definition and Relationships with Local Geodetic Systems (National Geospatial-Intelligence Agency (NGA))
- GeoNames geographical database (GeoNames)
- curl manual page (--write-out variables) (curl project)
- Teach Yourself Programming in Ten Years (approximate timings) (Peter Norvig)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress