Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

System Design (High-Level Design)  Module 2 – Back-of-the-envelope estimation

Units, powers of two and time conversions

Convert decimal and binary units such as GB and GiB, turn daily counts into rates per second and round estimates on purpose, with scripts that check the maths.

  • Beginner
  • 15 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free lesson, Pro answers: 15 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Convert between decimal units (kB, MB, GB) and binary units (KiB, MiB, GiB) without mixing them
  • Convert link rates in bits per second into bytes per second and work out a transfer's best-case time
  • Work out how long a 32-bit or 64-bit ID counter lasts at a given rate of new IDs
  • Convert per-day and per-month counts into average rates per second
  • Estimate with one or two significant figures and say which way each rounding pushes the result

Before you start

What you’ll learn · Before you start

What you will learn

  • Convert between decimal units (kB, MB, GB) and binary units (KiB, MiB, GiB) without mixing them
  • Convert link rates in bits per second into bytes per second and work out a transfer's best-case time
  • Work out how long a 32-bit or 64-bit ID counter lasts at a given rate of new IDs
  • Convert per-day and per-month counts into average rates per second
  • Estimate with one or two significant figures and say which way each rounding pushes the result

Before you start

On this page

A drive sold as 1 TB shows up as 931 GB in some tools, and a link rated at 1 Gbit/s copies at most 125 MB a second. Most estimates that go wrong in a design round go wrong in the units, not in the idea: a rate per minute read as a rate per second, gigabits taken for gigabytes, or a drive’s decimal terabytes compared with memory’s binary gibibytes.

This lesson settles the units first, so that every later estimate in this module stands on firm ground: the two families of size prefixes, bits and bytes, the powers of two that set real limits, the step from a daily count to a rate per second, and how to round without fooling yourself.

Decimal and binary prefixes drift apart at every step

Kilo, mega, giga, tera and peta are SI prefix: A prefix that multiplies a unit by a power of ten: kilo (k) is 10³, mega (M) 10⁶, giga (G) 10⁹ and tera (T) 10¹², so a kilobyte is 1,000 bytes and a gigabyte 10⁹ bytes., and SI prefixes are powers of ten: a kilobyte (kB) is 1,000 bytes and a gigabyte (GB) is 10910^{9} bytes (NIST, SI prefixes). Computer memory is built in powers of two, because its addresses are binary numbers, so a second family of prefixes names exact binary multiples: kibi (Ki, 2102^{10}), mebi (Mi, 2202^{20}), gibi (Gi, 2302^{30}), tebi (Ti) and pebi (Pi). The IEC defined these binary prefix (IEC): A prefix for a power of two: kibi (Ki) is 2¹⁰ = 1,024, mebi (Mi) 2²⁰, gibi (Gi) 2³⁰ and tebi (Ti) 2⁴⁰. A gibibyte is 1,073,741,824 bytes, 7.4 % more than a gigabyte., and they are not part of the SI (NIST, binary prefixes). Watch the letter case: the decimal kilo is a lowercase k (kB), the binary kibi a capital K (KiB).

How far apart the two families drift Python · units/prefixes.py
# Decimal (SI) prefixes are powers of 10; binary (IEC) prefixes are powers of 2.
# The two families start close together and drift apart with every step.
PREFIXES = [("kilo", "kB", "KiB"), ("mega", "MB", "MiB"), ("giga", "GB", "GiB"), ("tera", "TB", "TiB"), ("peta", "PB", "PiB"), ("exa", "EB", "EiB")]

print(f"{'Prefix':<8}{'Decimal':<13}{'Binary':<13}{'Gap':>6}")
for step, (name, dec, binary) in enumerate(PREFIXES, start=1):
    gap = (2 ** (10 * step) / 10 ** (3 * step) - 1) * 100
    print(f"{name:<8}{dec:<3} = 10^{3 * step:<4}{binary:<3} = 2^{10 * step:<5}{gap:5.1f}%")
print("Gap: how much bigger the binary unit is than the decimal one")

print()
print(f"1 GB  = {10**9:>13,} bytes")
print(f"1 GiB = {2**30:>13,} bytes")
disk = 10**12  # a drive sold as "1 TB"
print(f'A "1 TB" drive holds {disk / 2**30:.1f} GiB, which is {disk / 2**40:.3f} TiB')

Output

Prefix  Decimal      Binary          Gap
kilo    kB  = 10^3   KiB = 2^10     2.4%
mega    MB  = 10^6   MiB = 2^20     4.9%
giga    GB  = 10^9   GiB = 2^30     7.4%
tera    TB  = 10^12  TiB = 2^40    10.0%
peta    PB  = 10^15  PiB = 2^50    12.6%
exa     EB  = 10^18  EiB = 2^60    15.3%
Gap: how much bigger the binary unit is than the decimal one

1 GB  = 1,000,000,000 bytes
1 GiB = 1,073,741,824 bytes
A "1 TB" drive holds 931.3 GiB, which is 0.909 TiB

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 prefixes.py

The two start 2.4% apart and drift further with every step: a tebibyte is 10% bigger than a terabyte, a pebibyte 12.6% bigger than a petabyte. The last line explains a familiar puzzle. A program that divides a byte count by 2302^{30} but prints the label “GB” shows a 1 TB drive as about 931 GB. No space is missing; the unit changed and the label did not. Step through the same terabyte counted in binary units, one division by 1,024 at a time, and watch the gap grow:

Interactive · stage by stage One terabyte counted in binary units Step through the same 10¹² bytes divided by 1,024 at every step instead of 1,000, and watch the gap grow.
One terabyte counted in binary units, step 6 of 6. Showing 1 TB = 10¹² bytes, 976,562,500 KiB, 953,674.3 MiB, 931.3 GiB, 0.909 TiB. In focus: 0.909 TiB.1 TB = 10¹² bytesdecimal: 1,000 GB976,562,500 KiBdecimal: 1,000,000,000 kB953,674.3 MiBdecimal: 1,000,000 MB931.3 GiBdecimal: 1,000 GB0.909 TiBdecimal: 1 TB

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The bytes on the label. A drive maker counts in SI units, so 1 TB is 10¹² bytes, which is also 1,000 GB. Those bytes never change in the steps below; only the unit they are counted in does.
  2. Kibibytes. Divide by 1,024 instead of 1,000 and the same bytes are 976,562,500 KiB. A kibibyte is 2.4 % bigger than a kilobyte, so the count comes out 2.3 % smaller.
  3. Mebibytes. Divide by 1,024 again and they are 953,674.3 MiB. The gaps multiply, so a mebibyte is already 4.9 % bigger than a megabyte.
  4. Gibibytes. A third division gives 931.3 GiB, 6.9 % below the 1,000 GB on the label, because a gibibyte is 7.4 % bigger than a gigabyte.
  5. The label that did not change. Software that divides by 2³⁰ but keeps the label GB shows this drive as 931 GB. Nothing is missing; the unit changed and the label did not.
  6. Tebibytes. At the last step the drive holds 0.909 TiB. A tebibyte is 10 % bigger than a terabyte, the gap the table above printed for tera.

NIST’s page records the same split in practice: memory makers have used the binary megabyte, and storage makers usually the decimal one.

In an estimate, choose one family and say which. Decimal units are easier to multiply in your head, and for most estimates the gap is smaller than the uncertainty in the assumptions. Switch to binary units when the thing you are sizing is counted in binary: memory, page and block sizes, and any limit that a system documents in KiB or MiB.

A program computes the same thing whichever family you meant, so a mix-up gives no error, only a wrong number:

Decimal bytes divided by a binary unit Python · units/mixup.py
disk_bytes = 500 * 10**9  # a drive sold as "500 GB" (decimal units)
print(round(disk_bytes / 2**30, 1), "GiB")

Output

465.7 GiB

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 mixup.py

Key idea

A kilobyte is 1,000 bytes and a kibibyte 1,024. The gap between the two families grows from 2.4 % at kilo to 10 % at tera, so name the family before you give the number.

Checkpoint

Check: Decimal and binary prefixes

  1. Question 1 of 2 A drive is sold as 4 TB, in decimal units. How many TiB does it hold?

    Type a number.

    A hint

    1 TiB is 2⁴⁰ = 1,099,511,627,776 bytes.

    Show the answer: Question 1 of 2

    Answer: 3.64 TiB (anything from 3.62 to 3.66 counts)

    4 TB is 4 × 10¹² bytes, and 4 × 10¹² ÷ 2⁴⁰ ≈ 3.64 TiB. The bytes are the same; the binary unit is 10 % bigger than the decimal one, so the count comes out about 9 % smaller.

  2. Question 2 of 2 You are sizing how many cache entries fit in a server's 64 GiB of RAM. Which family of units should the estimate use for the memory?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Binary units, because memory is built and documented in powers of two

    Use binary units for whatever is counted in binary: memory, page and block sizes, and limits documented in KiB or MiB. Say which family you use, so nobody reads 64 GiB as 64 × 10⁹ bytes.

A byte is 8 bits (NIST). Files, disks and memory are counted in bytes, written with a capital B, but links are rated in bits per second, written with a lowercase b: the IEEE 802.3 working group names Ethernet speeds such as 400 Gb/s. Confusing the two puts an estimate out by exactly a factor of eight.

What a 1 Gbit/s link can move Python · units/link_speed.py
# Links are rated in bits per second; files and disks are measured in bytes.
BITS_PER_BYTE = 8

link_bits_per_s = 1 * 10**9  # a "1 Gbit/s" link
bytes_per_s = link_bits_per_s / BITS_PER_BYTE
print(f"1 Gbit/s carries at most {bytes_per_s / 10**6:.0f} MB/s ({bytes_per_s / 2**20:.1f} MiB/s)")

file_bytes = 1 * 10**12  # copying "1 TB"
seconds = file_bytes / bytes_per_s
print(f"Copying 1 TB over it takes at least {seconds:,.0f} s, about {seconds / 3600:.1f} hours")
print(f"Forgetting the 8 would promise {file_bytes / link_bits_per_s:,.0f} s instead")

Output

1 Gbit/s carries at most 125 MB/s (119.2 MiB/s)
Copying 1 TB over it takes at least 8,000 s, about 2.2 hours
Forgetting the 8 would promise 1,000 s instead

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 link_speed.py

Treat a link’s rating as a ceiling, not a promise: the same link also carries protocol headers, other traffic and retransmissions, so a real copy takes longer than the time computed here. The figure is still useful, because it is a lower bound. If even the best case is too slow, no tuning will rescue the design.

Checkpoint

Check: Bits per second and bytes

  1. One question At best, how many hours does copying 2 TB take over a link rated at 1 Gbit/s?

    Type a number.

    A hint

    Turn the link's bits per second into bytes per second first.

    Show the answer: One question

    Answer: 4.44 hours (anything from 4.34 to 4.54 counts)

    1 Gbit/s carries at most 125 MB a second, and 2 × 10¹² bytes ÷ 125 × 10⁶ bytes a second = 16,000 s, about 4.4 hours. That is a floor: headers, other traffic and retransmissions make the real copy slower.

Powers of two set the limits of counters and IDs

Ten doublings make about a thousand, because 210=10242^{10} = 1024. Twenty doublings make about a million and thirty about a billion. Two more powers turn up in designs because they are the sizes of common integer types: a 32-bit unsigned integer has 2322^{32} possible values and a 64-bit one 2642^{64}. The program below prints these powers in 14 languages, each with its own integer types, and works out how long a counter of each width lasts before its ID space: All the values an identifier can take. A 32-bit counter has 2³² = 4,294,967,296 of them; once they are used up, new records need a wider type or another scheme. is used up:

One program · 14 languages Powers of two, and how long an ID space lasts

Python 3.14 · main.py

# Powers of two worth knowing, and how long an ID space lasts.
SECONDS_PER_DAY = 86_400
SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY

for exponent in [10, 16, 20, 30, 32, 40]:
    print(f"2^{exponent} = {2**exponent:>17,}")
print(f"2^63 - 1 = {2**63 - 1:,}, the largest signed 64-bit integer")

print()
days = 2**32 / 1_000 / SECONDS_PER_DAY
print(f"A 32-bit counter, 1,000 new IDs a second: full after {days:.1f} days")
years = 2**64 / 1_000_000 / SECONDS_PER_YEAR
print(f"A 64-bit counter, 1 million new IDs a second: full after {years:,.0f} years")
print(f"7-character codes from 62 letters and digits: {62**7:,}")

In Python: Integers have no fixed width, so 2**63 - 1 and 2**64 are exact; 2**64 / 1_000_000 then divides as floating point, and :.1f rounds the days to one decimal.

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

// Powers of two worth knowing, and how long an ID space lasts.
const SECONDS_PER_DAY = 86_400;
const SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY;

// A whole number with a comma between each group of three digits.
const group = (n) => String(n).replace(/\B(?=(\d{3})+$)/g, ",");

for (const exponent of [10, 16, 20, 30, 32, 40]) {
  console.log(`2^${exponent} = ${group(2 ** exponent).padStart(17)}`);
}
console.log(`2^63 - 1 = ${group(2n ** 63n - 1n)}, the largest signed 64-bit integer`);

console.log();
const days = 2 ** 32 / 1_000 / SECONDS_PER_DAY;
console.log(`A 32-bit counter, 1,000 new IDs a second: full after ${days.toFixed(1)} days`);
const years = 2 ** 64 / 1_000_000 / SECONDS_PER_YEAR;
const lifetime = group(Math.round(years));
console.log(`A 64-bit counter, 1 million new IDs a second: full after ${lifetime} years`);
let codes = 1;
for (let i = 0; i < 7; i++) {
  codes *= 62;
}
console.log(`7-character codes from 62 letters and digits: ${group(codes)}`);

In JavaScript: A Number holds whole numbers exactly only up to 2^53 − 1, so the largest 64-bit integer is worked out as a BigInt, 2n ** 63n - 1n; every other value here stays below that.

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;

// Powers of two worth knowing, and how long an ID space lasts.
public class Main {
  static final int SECONDS_PER_DAY = 86_400;
  static final int SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY;

  public static void main(String[] args) {
    Locale.setDefault(Locale.ROOT);
    for (int exponent : new int[] {10, 16, 20, 30, 32, 40}) {
      System.out.printf("2^%d = %,17d%n", exponent, 1L << exponent);
    }
    System.out.printf("2^63 - 1 = %,d, the largest signed 64-bit integer%n", Long.MAX_VALUE);

    System.out.println();
    double days = (double) (1L << 32) / 1_000 / SECONDS_PER_DAY;
    System.out.printf("A 32-bit counter, 1,000 new IDs a second: full after %.1f days%n", days);
    double years = 0x1p64 / 1_000_000 / SECONDS_PER_YEAR;
    System.out.printf(
        "A 64-bit counter, 1 million new IDs a second: full after %,.0f years%n", years);
    long codes = 1;
    for (int i = 0; i < 7; i++) {
      codes *= 62;
    }
    System.out.printf("7-character codes from 62 letters and digits: %,d%n", codes);
  }
}

In Java: 1L << exponent shifts a long; on an int, 1 << 32 gives 1, because the shift distance is taken modulo 32. 0x1p64 is the double 2^64 written in hexadecimal, and Long.MAX_VALUE is 2^63 − 1.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. To run it yourself: java Main.java

C++23 · main.cpp

// Powers of two worth knowing, and how long an ID space lasts.
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <print>
#include <string>

constexpr std::int64_t seconds_per_day = 86'400;
constexpr std::int64_t seconds_per_year = 365 * seconds_per_day;

// A whole number with a comma between each group of three digits.
std::string group(std::int64_t n) {
  std::string digits = std::to_string(n);
  for (auto i = static_cast<std::ptrdiff_t>(digits.size()) - 3; i > 0; i -= 3) {
    digits.insert(static_cast<std::size_t>(i), ",");
  }
  return digits;
}

int main() {
  constexpr std::array exponents{10, 16, 20, 30, 32, 40};
  for (const int exponent : exponents) {
    std::println("2^{} = {:>17}", exponent, group(std::int64_t{1} << exponent));
  }
  std::println("2^63 - 1 = {}, the largest signed 64-bit integer",
               group(std::numeric_limits<std::int64_t>::max()));

  std::println();
  const double days =
      static_cast<double>(std::int64_t{1} << 32) / 1'000 / seconds_per_day;
  std::println(
      "A 32-bit counter, 1,000 new IDs a second: full after {:.1f} days", days);
  const double years = 0x1p64 / 1'000'000 / seconds_per_year;
  std::println(
      "A 64-bit counter, 1 million new IDs a second: full after {} years",
      group(std::llround(years)));
  std::int64_t codes = 1;
  for (int i = 0; i < 7; i++) {
    codes *= 62;
  }
  std::println("7-character codes from 62 letters and digits: {}",
               group(codes));
}

In C++: std::int64_t{1} << exponent shifts a 64-bit value, 0x1p64 is a hexadecimal floating literal for 2^64, and std::llround rounds the years to a whole number.

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

// Powers of two worth knowing, and how long an ID space lasts.
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

const int SecondsPerDay = 86_400;
const int SecondsPerYear = 365 * SecondsPerDay;

int[] exponents = [10, 16, 20, 30, 32, 40];
foreach (int exponent in exponents)
{
    Console.WriteLine($"2^{exponent} = {1L << exponent,17:N0}");
}
Console.WriteLine($"2^63 - 1 = {long.MaxValue:N0}, the largest signed 64-bit integer");

Console.WriteLine();
double days = (double)(1L << 32) / 1_000 / SecondsPerDay;
Console.WriteLine($"A 32-bit counter, 1,000 new IDs a second: full after {days:F1} days");
double years = Math.Pow(2, 64) / 1_000_000 / SecondsPerYear;
Console.WriteLine($"A 64-bit counter, 1 million new IDs a second: full after {years:N0} years");
long codes = 1;
for (int i = 0; i < 7; i++)
{
    codes *= 62;
}
Console.WriteLine($"7-character codes from 62 letters and digits: {codes:N0}");

In C#: 1L << exponent shifts a long, and N0 groups the digits; Math.Pow(2, 64) is exact, since a double holds every power of two in its range.

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

// Powers of two worth knowing, and how long an ID space lasts.
#include <inttypes.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

constexpr int64_t seconds_per_day = 86400;
constexpr int64_t seconds_per_year = 365 * seconds_per_day;

// A whole number with a comma between each group of three digits.
static void group(int64_t n, char out[static 32]) {
  char digits[24];
  const int len = snprintf(digits, sizeof digits, "%" PRId64, n);
  int j = 0;
  for (int i = 0; i < len; i++) {
    if (i > 0 && (len - i) % 3 == 0) {
      out[j++] = ',';
    }
    out[j++] = digits[i];
  }
  out[j] = '\0';
}

int main(void) {
  static const int exponents[] = {10, 16, 20, 30, 32, 40};
  char text[32];
  for (size_t i = 0; i < sizeof exponents / sizeof exponents[0]; i++) {
    group(INT64_C(1) << exponents[i], text);
    printf("2^%d = %17s\n", exponents[i], text);
  }
  group(INT64_MAX, text);
  printf("2^63 - 1 = %s, the largest signed 64-bit integer\n", text);

  puts("");
  const double days = (double)(INT64_C(1) << 32) / 1000 / seconds_per_day;
  printf("A 32-bit counter, 1,000 new IDs a second: full after %.1f days\n",
         days);
  const double years = 0x1p64 / 1000000 / seconds_per_year;
  group(llround(years), text);
  printf("A 64-bit counter, 1 million new IDs a second: full after %s years\n",
         text);
  int64_t codes = 1;
  for (int i = 0; i < 7; i++) {
    codes *= 62;
  }
  group(codes, text);
  printf("7-character codes from 62 letters and digits: %s\n", text);
  return 0;
}

In C: INT64_C(1) << exponents[i] shifts a 64-bit value, INT64_MAX is 2^63 − 1, and 0x1p64 is a hexadecimal floating constant for 2^64.

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

// Powers of two worth knowing, and how long an ID space lasts.

declare(strict_types=1);

const SECONDS_PER_DAY = 86_400;
const SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY;

foreach ([10, 16, 20, 30, 32, 40] as $exponent) {
    printf("2^%d = %17s\n", $exponent, number_format(2 ** $exponent));
}
printf("2^63 - 1 = %s, the largest signed 64-bit integer\n", number_format(PHP_INT_MAX));

echo "\n";
$days = 2 ** 32 / 1_000 / SECONDS_PER_DAY;
printf("A 32-bit counter, 1,000 new IDs a second: full after %.1f days\n", $days);
$years = 2 ** 64 / 1_000_000 / SECONDS_PER_YEAR;
$lifetime = number_format($years);
printf("A 64-bit counter, 1 million new IDs a second: full after %s years\n", $lifetime);
printf("7-character codes from 62 letters and digits: %s\n", number_format(62 ** 7));

In PHP: 2 ** 64 does not fit an int, so PHP turns it into a float by itself. PHP_INT_MAX is the largest int of the build, 2^63 − 1 where integers have 64 bits and 2^31 − 1 where they have 32.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. To run it yourself: php main.php

Rust 1.99 · main.rs

// Powers of two worth knowing, and how long an ID space lasts.
const SECONDS_PER_DAY: i64 = 86_400;
const SECONDS_PER_YEAR: i64 = 365 * SECONDS_PER_DAY;

/// A whole number with a comma between each group of three digits.
fn group(n: i64) -> String {
    let digits = n.to_string();
    let mut out = String::new();
    for (i, digit) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(digit);
    }
    out
}

fn main() {
    for exponent in [10, 16, 20, 30, 32, 40] {
        println!("2^{exponent} = {:>17}", group(1_i64 << exponent));
    }
    println!(
        "2^63 - 1 = {}, the largest signed 64-bit integer",
        group(i64::MAX)
    );

    println!();
    let days = (1_i64 << 32) as f64 / 1_000.0 / SECONDS_PER_DAY as f64;
    println!("A 32-bit counter, 1,000 new IDs a second: full after {days:.1} days");
    let years = 2_f64.powi(64) / 1_000_000.0 / SECONDS_PER_YEAR as f64;
    let lifetime = group(years.round() as i64);
    println!("A 64-bit counter, 1 million new IDs a second: full after {lifetime} years");
    let codes = 62_i64.pow(7);
    println!(
        "7-character codes from 62 letters and digits: {}",
        group(codes)
    );
}

In Rust: 1_i64 << exponent and 62_i64.pow(7) are exact integer operations, i64::MAX is 2^63 − 1, and 2_f64.powi(64) is 2^64 as an f64.

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

// Powers of two worth knowing, and how long an ID space lasts.
const SECONDS_PER_DAY = 86_400;
const SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY;

// A whole number with a comma between each group of three digits.
const group = (n: number | bigint): string => String(n).replace(/\B(?=(\d{3})+$)/g, ",");

for (const exponent of [10, 16, 20, 30, 32, 40]) {
  console.log(`2^${exponent} = ${group(2 ** exponent).padStart(17)}`);
}
console.log(`2^63 - 1 = ${group(2n ** 63n - 1n)}, the largest signed 64-bit integer`);

console.log();
const days = 2 ** 32 / 1_000 / SECONDS_PER_DAY;
console.log(`A 32-bit counter, 1,000 new IDs a second: full after ${days.toFixed(1)} days`);
const years = 2 ** 64 / 1_000_000 / SECONDS_PER_YEAR;
const lifetime = group(Math.round(years));
console.log(`A 64-bit counter, 1 million new IDs a second: full after ${lifetime} years`);
let codes = 1;
for (let i = 0; i < 7; i++) {
  codes *= 62;
}
console.log(`7-character codes from 62 letters and digits: ${group(codes)}`);

In TypeScript: BigInt literals such as 2n need ES2020 or later, and group takes a number or a bigint, since String writes both out in full.

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

// Powers of two worth knowing, and how long an ID space lasts.
package main

import (
	"fmt"
	"math"
	"strconv"
	"strings"
)

const (
	secondsPerDay  = 86_400
	secondsPerYear = 365 * secondsPerDay
)

// group writes a whole number with a comma between each group of three digits.
func group(n int64) string {
	digits := strconv.FormatInt(n, 10)
	var b strings.Builder
	for i, d := range digits {
		if i > 0 && (len(digits)-i)%3 == 0 {
			b.WriteByte(',')
		}
		b.WriteRune(d)
	}
	return b.String()
}

func main() {
	for _, exponent := range []int{10, 16, 20, 30, 32, 40} {
		fmt.Printf("2^%d = %17s\n", exponent, group(int64(1)<<exponent))
	}
	fmt.Printf("2^63 - 1 = %s, the largest signed 64-bit integer\n", group(math.MaxInt64))

	fmt.Println()
	days := float64(int64(1)<<32) / 1_000 / secondsPerDay
	fmt.Printf("A 32-bit counter, 1,000 new IDs a second: full after %.1f days\n", days)
	years := 0x1p64 / 1_000_000 / secondsPerYear
	lifetime := group(int64(math.Round(years)))
	fmt.Printf("A 64-bit counter, 1 million new IDs a second: full after %s years\n", lifetime)
	codes := int64(1)
	for range 7 {
		codes *= 62
	}
	fmt.Printf("7-character codes from 62 letters and digits: %s\n", group(codes))
}

In Go: math.MaxInt64 is an untyped constant, 0x1p64 is a hexadecimal float literal, and for range 7, new in Go 1.22, repeats the multiplication seven times.

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

// Powers of two worth knowing, and how long an ID space lasts.
let secondsPerDay: Int64 = 86_400
let secondsPerYear = 365 * secondsPerDay

/// A whole number with a comma between each group of three digits.
func group(_ n: Int64) -> String {
  let digits = Array(String(n))
  var out = ""
  for (i, digit) in digits.enumerated() {
    if i > 0 && (digits.count - i) % 3 == 0 {
      out.append(",")
    }
    out.append(digit)
  }
  return out
}

// Padding by hand: without Foundation the standard library has no String(format:).
func padLeft(_ text: String, to width: Int) -> String {
  String(repeating: " ", count: max(0, width - text.count)) + text
}

for exponent in [10, 16, 20, 30, 32, 40] {
  print("2^\(exponent) = \(padLeft(group(Int64(1) << exponent), to: 17))")
}
print("2^63 - 1 = \(group(Int64.max)), the largest signed 64-bit integer")

print()
let days = Double(Int64(1) << 32) / 1_000 / Double(secondsPerDay)
let tenths = Int64((days * 10).rounded())
print("A 32-bit counter, 1,000 new IDs a second: full after \(tenths / 10).\(tenths % 10) days")
let years = 0x1p64 / 1_000_000 / Double(secondsPerYear)
let lifetime = group(Int64(years.rounded()))
print("A 64-bit counter, 1 million new IDs a second: full after \(lifetime) years")
var codes: Int64 = 1
for _ in 1...7 {
  codes *= 62
}
print("7-character codes from 62 letters and digits: \(group(codes))")

In Swift: Int64 keeps 2^40 and 2^63 − 1 in range in the WebAssembly build too, where Int has 32 bits; 0x1p64 is a hexadecimal float literal, and the days are rounded as tenths because there is no String(format:).

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

# Powers of two worth knowing, and how long an ID space lasts.
SECONDS_PER_DAY = 86_400
SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY

# A whole number with a comma between each group of three digits.
def group(number) = number.to_s.gsub(/\B(?=(\d{3})+$)/, ',')

[10, 16, 20, 30, 32, 40].each do |exponent|
  puts "2^#{exponent} = #{group(2**exponent).rjust(17)}"
end
puts "2^63 - 1 = #{group((2**63) - 1)}, the largest signed 64-bit integer"

puts
days = (2**32).fdiv(1_000) / SECONDS_PER_DAY
puts "A 32-bit counter, 1,000 new IDs a second: full after #{format('%.1f', days)} days"
years = (2**64).fdiv(1_000_000) / SECONDS_PER_YEAR
puts "A 64-bit counter, 1 million new IDs a second: full after #{group(years.round)} years"
puts "7-character codes from 62 letters and digits: #{group(62**7)}"

In Ruby: Integers grow as large as they need to, so 2**64 is exact and fdiv divides it as floating point; with no fixed 64-bit type, the largest signed 64-bit integer is written as 2**63 - 1.

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.pow
import kotlin.math.roundToLong

// Powers of two worth knowing, and how long an ID space lasts.
const val SECONDS_PER_DAY = 86_400L
const val SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY

// A whole number with a comma between each group of three digits.
fun Long.group() =
    toString()
        .reversed()
        .chunked(3)
        .joinToString(",")
        .reversed()

fun main() {
    for (exponent in intArrayOf(10, 16, 20, 30, 32, 40)) {
        println("2^$exponent = ${(1L shl exponent).group().padStart(17)}")
    }
    println("2^63 - 1 = ${Long.MAX_VALUE.group()}, the largest signed 64-bit integer")

    println()
    val days = (1L shl 32).toDouble() / 1_000 / SECONDS_PER_DAY
    val tenths = (days * 10).roundToLong()
    val days32 = "${tenths / 10}.${tenths % 10}"
    println("A 32-bit counter, 1,000 new IDs a second: full after $days32 days")
    val years = 2.0.pow(64) / 1_000_000 / SECONDS_PER_YEAR
    val years64 = years.roundToLong().group()
    println("A 64-bit counter, 1 million new IDs a second: full after $years64 years")
    var codes = 1L
    repeat(7) { codes *= 62 }
    println("7-character codes from 62 letters and digits: ${codes.group()}")
}

In Kotlin: 1L shl exponent shifts a Long and Long.MAX_VALUE is 2^63 − 1; with no String.format in the common standard library, the days are rounded as a whole number of tenths.

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';

// Powers of two worth knowing, and how long an ID space lasts.
const secondsPerDay = 86_400;
const secondsPerYear = 365 * secondsPerDay;

/// A whole number with a comma between each group of three digits.
String group(int n) => n.toString().replaceAll(RegExp(r'\B(?=(\d{3})+$)'), ',');

void main() {
  for (final exponent in [10, 16, 20, 30, 32, 40]) {
    print('2^$exponent = ${group(1 << exponent).padLeft(17)}');
  }
  print(
    '2^63 - 1 = ${group(0x7FFFFFFFFFFFFFFF)}, the largest signed 64-bit integer',
  );

  print('');
  final days = (1 << 32) / 1_000 / secondsPerDay;
  print(
    'A 32-bit counter, 1,000 new IDs a second: '
    'full after ${days.toStringAsFixed(1)} days',
  );
  final years = pow(2.0, 64) / 1_000_000 / secondsPerYear;
  print(
    'A 64-bit counter, 1 million new IDs a second: '
    'full after ${group(years.round())} years',
  );
  final codes = pow(62, 7).toInt();
  print('7-character codes from 62 letters and digits: ${group(codes)}');
}

In Dart: An int has 64 bits and no named maximum, so 0x7FFFFFFFFFFFFFFF writes 2^63 − 1. pow(2.0, 64) starts from a double, because pow(2, 64) on two ints wraps round to 0.

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

2^10 =             1,024
2^16 =            65,536
2^20 =         1,048,576
2^30 =     1,073,741,824
2^32 =     4,294,967,296
2^40 = 1,099,511,627,776
2^63 - 1 = 9,223,372,036,854,775,807, the largest signed 64-bit integer

A 32-bit counter, 1,000 new IDs a second: full after 49.7 days
A 64-bit counter, 1 million new IDs a second: full after 584,942 years
7-character codes from 62 letters and digits: 3,521,614,606,208

These limits decide real designs. A 32-bit counter that hands out 1,000 IDs a second runs out in under two months, while a 64-bit counter at a million a second outlasts any system you will build. Short codes work the same way: seven characters drawn from 62 letters and digits give about 3.5 trillion codes, which is why a link shortener’s links can stay short for a very long time. A signed 32-bit integer has half the range of an unsigned one, up to 2,147,483,647, so the same 1,000 IDs a second fill it in about 25 days.

The width matters again when an ID leaves the server. JSON numbers are reliably exchanged as integers only up to 253−12^{53} - 1, the range in which, as RFC 8259 puts it, implementations “will agree exactly on their numeric values” (RFC 8259, section 6). JavaScript’s numbers are exact only that far too (MDN), which is why its version of the program needs a BigInt for 263−12^{63} - 1. A 64-bit ID sent as a JSON number can therefore reach a browser with its last digits changed; send such IDs as strings.

Checkpoint

Check: Powers of two and ID spaces

  1. Question 1 of 2 An unsigned 32-bit counter hands out 100 IDs a second. After about how many days are all its 2³² values used?

    Type a number.

    A hint

    2³² is about 4.3 billion, and a day has 86,400 seconds.

    Show the answer: Question 1 of 2

    Answer: 497 days (anything from 492 to 502 counts)

    4,294,967,296 ÷ 100 ÷ 86,400 ≈ 497 days, under a year and a half. At 1,000 IDs a second, as in the program, it is 49.7 days; a 64-bit counter at the same rates would outlast any system.

  2. Question 2 of 2 An API returns 64-bit order IDs as JSON numbers, and a browser client shows some IDs with their last digits changed. What is the fix?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Send the IDs as JSON strings

    JSON parsers in JavaScript read numbers as doubles, which hold whole numbers exactly only up to 2⁵³ − 1, so a 64-bit ID can arrive changed. Sending it as a string keeps all its digits.

A day has 86,400 seconds: from a daily count to a rate

Requirements usually arrive as counts per day or per month (“20 million messages a day”), while servers, databases and queues are sized in operations per second. A day has 24×60×60=8640024 \times 60 \times 60 = 86400 seconds, and the rest follows from it. Follow that requirement down to a rate per second:

Interactive · stage by stage 20 million messages a day, as a rate per second Step through one requirement divided by the hours, minutes and seconds of a day, 86,400 seconds in all.
20 million messages a day, as a rate per second, step 5 of 5. Showing 20,000,000 a day, 833,333 an hour, 13,889 a minute, 231.5 a second. In focus: 231.5 a second.20,000,000 a daythe requirement833,333 an hour÷ 24 hours13,889 a minute÷ 60 minutes231.5 a second÷ 60 secondsthe average over 24 hours

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. The requirement. The product team says 20 million messages a day. That is a count per day, while servers, databases and queues are sized in operations per second.
  2. Per hour. Spread evenly over the 24 hours of a day, 20 million messages are 833,333 an hour.
  3. Per minute. Divided by the 60 minutes of an hour, that is 13,889 a minute, the unit many rate limits are written in.
  4. Per second. Divided by 60 once more, it is 231.5 a second. The three steps together divided by 24 × 60 × 60 = 86,400, the seconds in a day.
  5. An average, not a peak. 231.5 a second is the average over the whole day, night included. The busiest hour brings more than that, which is why the lesson on estimating traffic turns an average into a peak.

The same division, for every period an estimate uses and for daily counts from a million to ten billion:

One program · 14 languages Seconds per period, and daily counts as rates

Python 3.14 · main.py

# Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
# and daily counts as average rates per second.
MINUTE = 60
HOUR = 60 * MINUTE
DAY = 24 * HOUR
MONTH = 30 * DAY
YEAR = 365 * DAY

PERIODS = [
    ("minute", MINUTE),
    ("hour", HOUR),
    ("day", DAY),
    ("30-day month", MONTH),
    ("365-day year", YEAR),
]
DAILY_COUNTS = [1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000]

for name, seconds in PERIODS:
    print(f"1 {name:<13} = {seconds:>10,} s")

print()
print(f"{'Events a day':>16}  {'average per second':>18}")
for per_day in DAILY_COUNTS:
    print(f"{per_day:>16,}  {per_day / DAY:>18,.1f}")

print()
monthly = 3_000_000_000  # an example: 3 billion events in a 30-day month
print(f"3 billion a month = {monthly / MONTH:,.0f} per second on average")
# Dividing one whole number by another in integer arithmetic drops the fraction.
print(f"1,000,000 a day in integer division: {1_000_000 // DAY} per second, not 11.6")

In Python: / always divides as floating point, so per_day / DAY keeps its fraction and // is the integer division; the format spec ,.1f rounds to one decimal and groups the digits in one step.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const MONTH = 30 * DAY;
const YEAR = 365 * DAY;

const PERIODS = [
  ["minute", MINUTE],
  ["hour", HOUR],
  ["day", DAY],
  ["30-day month", MONTH],
  ["365-day year", YEAR],
];
const DAILY_COUNTS = [1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000];

// x rounded to the given decimals, with commas between groups of three digits.
function grouped(x, decimals = 0) {
  const parts = x.toFixed(decimals).split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+$)/g, ",");
  return parts.join(".");
}

for (const [name, seconds] of PERIODS) {
  console.log(`1 ${name.padEnd(13)} = ${grouped(seconds).padStart(10)} s`);
}

console.log();
console.log(`${"Events a day".padStart(16)}  ${"average per second".padStart(18)}`);
for (const perDay of DAILY_COUNTS) {
  console.log(`${grouped(perDay).padStart(16)}  ${grouped(perDay / DAY, 1).padStart(18)}`);
}

console.log();
const monthly = 3_000_000_000; // an example: 3 billion events in a 30-day month
console.log(`3 billion a month = ${grouped(monthly / MONTH)} per second on average`);
// Dividing one whole number by another in integer arithmetic drops the fraction.
const truncated = Math.trunc(1_000_000 / DAY);
console.log(`1,000,000 a day in integer division: ${truncated} per second, not 11.6`);

In JavaScript: Every number is a double, so / never drops a fraction and JavaScript has no integer division of its own; Math.trunc(1_000_000 / DAY) gives one.

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.List;
import java.util.Locale;

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
public class Main {
  static final int MINUTE = 60;
  static final int HOUR = 60 * MINUTE;
  static final int DAY = 24 * HOUR;
  static final int MONTH = 30 * DAY;
  static final int YEAR = 365 * DAY;

  record Period(String name, int seconds) {}

  public static void main(String[] args) {
    Locale.setDefault(Locale.ROOT);
    List<Period> periods =
        List.of(
            new Period("minute", MINUTE),
            new Period("hour", HOUR),
            new Period("day", DAY),
            new Period("30-day month", MONTH),
            new Period("365-day year", YEAR));
    long[] dailyCounts = {1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000L};

    for (Period period : periods) {
      System.out.printf("1 %-13s = %,10d s%n", period.name(), period.seconds());
    }

    System.out.println();
    System.out.printf("%16s  %18s%n", "Events a day", "average per second");
    for (long perDay : dailyCounts) {
      System.out.printf("%,16d  %,18.1f%n", perDay, (double) perDay / DAY);
    }

    System.out.println();
    long monthly = 3_000_000_000L; // an example: 3 billion events in a 30-day month
    System.out.printf(
        "3 billion a month = %,.0f per second on average%n", (double) monthly / MONTH);
    // Dividing one whole number by another in integer arithmetic drops the fraction.
    int truncated = 1_000_000 / DAY;
    System.out.printf("1,000,000 a day in integer division: %d per second, not 11.6%n", truncated);
  }
}

In Java: / between two integer types is integer division, so each rate casts the long perDay to double first; printf's , flag groups the digits, and Locale.ROOT makes the separator a comma.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. To run it yourself: java Main.java

C++23 · main.cpp

// Seconds in the periods that estimates use (a month taken as 30 days, a year
// as 365), and daily counts as average rates per second.
#include <array>
#include <cstddef>
#include <cstdint>
#include <format>
#include <print>
#include <string>
#include <string_view>
#include <utility>

constexpr std::int64_t minute = 60;
constexpr std::int64_t hour = 60 * minute;
constexpr std::int64_t day = 24 * hour;
constexpr std::int64_t month = 30 * day;
constexpr std::int64_t year = 365 * day;

// x rounded to the given decimals, with commas between groups of three
// digits.
std::string grouped(double x, int decimals = 0) {
  std::string text = std::format("{:.{}f}", x, decimals);
  const std::size_t point = text.find('.');
  const std::size_t whole = point == std::string::npos ? text.size() : point;
  for (auto i = static_cast<std::ptrdiff_t>(whole) - 3; i > 0; i -= 3) {
    text.insert(static_cast<std::size_t>(i), ",");
  }
  return text;
}

int main() {
  constexpr std::array<std::pair<std::string_view, std::int64_t>, 5> periods{{
      {"minute", minute},
      {"hour", hour},
      {"day", day},
      {"30-day month", month},
      {"365-day year", year},
  }};
  constexpr std::array<std::int64_t, 5> daily_counts{
      1'000'000, 10'000'000, 100'000'000, 1'000'000'000, 10'000'000'000};

  for (const auto &[name, seconds] : periods) {
    std::println("1 {:<13} = {:>10} s", name,
                 grouped(static_cast<double>(seconds)));
  }

  std::println();
  std::println("{:>16}  {:>18}", "Events a day", "average per second");
  for (const std::int64_t per_day : daily_counts) {
    const double rate = static_cast<double>(per_day) / day;
    std::println("{:>16}  {:>18}", grouped(static_cast<double>(per_day)),
                 grouped(rate, 1));
  }

  std::println();
  // An example: 3 billion events in a 30-day month.
  constexpr std::int64_t monthly = 3'000'000'000;
  std::println("3 billion a month = {} per second on average",
               grouped(static_cast<double>(monthly) / month));
  // Dividing one whole number by another in integer arithmetic drops the
  // fraction.
  constexpr std::int64_t truncated = 1'000'000 / day;
  std::println("1,000,000 a day in integer division: {} per second, not 11.6",
               truncated);
}

In C++: / between two integers drops the fraction, so each rate converts the count with static_cast<double> first; {:.{}f} takes the number of decimals as an argument.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

const int Minute = 60;
const int Hour = 60 * Minute;
const int Day = 24 * Hour;
const int Month = 30 * Day;
const int Year = 365 * Day;

(string Name, int Seconds)[] periods =
[
    ("minute", Minute),
    ("hour", Hour),
    ("day", Day),
    ("30-day month", Month),
    ("365-day year", Year),
];
long[] dailyCounts = [1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000];

foreach (var (name, seconds) in periods)
{
    Console.WriteLine($"1 {name,-13} = {seconds,10:N0} s");
}

Console.WriteLine();
Console.WriteLine($"{"Events a day",16}  {"average per second",18}");
foreach (long perDay in dailyCounts)
{
    double rate = (double)perDay / Day;
    Console.WriteLine($"{perDay,16:N0}  {rate,18:N1}");
}

Console.WriteLine();
long monthly = 3_000_000_000; // an example: 3 billion events in a 30-day month
Console.WriteLine($"3 billion a month = {(double)monthly / Month:N0} per second on average");
// Dividing one whole number by another in integer arithmetic drops the fraction.
int truncated = 1_000_000 / Day;
Console.WriteLine($"1,000,000 a day in integer division: {truncated} per second, not 11.6");

In C#: / between two integers drops the fraction, so each rate casts the count to double first; N0 and N1 round and group the digits with the invariant culture's comma.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year
// as 365), and daily counts as average rates per second.
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

constexpr int64_t minute = 60;
constexpr int64_t hour = 60 * minute;
constexpr int64_t day = 24 * hour;
constexpr int64_t month = 30 * day;
constexpr int64_t year = 365 * day;

typedef struct {
  const char *name;
  int64_t seconds;
} Period;

// x rounded to the given decimals, with commas between groups of three
// digits.
static void grouped(double x, int decimals, char out[static 40]) {
  char text[32];
  const int n = snprintf(text, sizeof text, "%.*f", decimals, x);
  const char *point = strchr(text, '.');
  const int whole = point ? (int)(point - text) : n;
  int j = 0;
  for (int i = 0; i < n; i++) {
    if (i > 0 && i < whole && (whole - i) % 3 == 0) {
      out[j++] = ',';
    }
    out[j++] = text[i];
  }
  out[j] = '\0';
}

int main(void) {
  static const Period periods[] = {
      {"minute", minute},      {"hour", hour},         {"day", day},
      {"30-day month", month}, {"365-day year", year},
  };
  static const int64_t daily_counts[] = {1000000, 10000000, 100000000,
                                         1000000000, 10000000000};
  char a[40];
  char b[40];

  for (size_t i = 0; i < sizeof periods / sizeof periods[0]; i++) {
    grouped((double)periods[i].seconds, 0, a);
    printf("1 %-13s = %10s s\n", periods[i].name, a);
  }

  puts("");
  printf("%16s  %18s\n", "Events a day", "average per second");
  for (size_t i = 0; i < sizeof daily_counts / sizeof daily_counts[0]; i++) {
    grouped((double)daily_counts[i], 0, a);
    grouped((double)daily_counts[i] / day, 1, b);
    printf("%16s  %18s\n", a, b);
  }

  puts("");
  // An example: 3 billion events in a 30-day month.
  const int64_t monthly = 3000000000;
  grouped((double)monthly / month, 0, a);
  printf("3 billion a month = %s per second on average\n", a);
  // Dividing one whole number by another in integer arithmetic drops the
  // fraction.
  const int64_t truncated = 1000000 / day;
  printf("1,000,000 a day in integer division: %" PRId64
         " per second, not 11.6\n",
         truncated);
  return 0;
}

In C: / between two integers drops the fraction, so the counts are cast to double first; %.*f takes the number of decimals as an argument, and PRId64 prints an int64_t.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.

declare(strict_types=1);

const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const MONTH = 30 * DAY;
const YEAR = 365 * DAY;

$periods = [
    'minute' => MINUTE,
    'hour' => HOUR,
    'day' => DAY,
    '30-day month' => MONTH,
    '365-day year' => YEAR,
];
$dailyCounts = [1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000];

foreach ($periods as $name => $seconds) {
    printf("1 %-13s = %10s s\n", $name, number_format($seconds));
}

echo "\n";
printf("%16s  %18s\n", 'Events a day', 'average per second');
foreach ($dailyCounts as $perDay) {
    printf("%16s  %18s\n", number_format($perDay), number_format($perDay / DAY, 1));
}

echo "\n";
$monthly = 3_000_000_000; // an example: 3 billion events in a 30-day month
printf("3 billion a month = %s per second on average\n", number_format($monthly / MONTH));
// Dividing one whole number by another in integer arithmetic drops the fraction.
$truncated = intdiv(1_000_000, DAY);
printf("1,000,000 a day in integer division: %d per second, not 11.6\n", $truncated);

In PHP: / returns a float whenever the division is not exact, so intdiv is the integer division here; number_format rounds and groups the digits.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
const MINUTE: u64 = 60;
const HOUR: u64 = 60 * MINUTE;
const DAY: u64 = 24 * HOUR;
const MONTH: u64 = 30 * DAY;
const YEAR: u64 = 365 * DAY;

const PERIODS: [(&str, u64); 5] = [
    ("minute", MINUTE),
    ("hour", HOUR),
    ("day", DAY),
    ("30-day month", MONTH),
    ("365-day year", YEAR),
];
const DAILY_COUNTS: [u64; 5] = [
    1_000_000,
    10_000_000,
    100_000_000,
    1_000_000_000,
    10_000_000_000,
];

/// x rounded to the given decimals, with commas between groups of three digits.
fn grouped(x: f64, decimals: usize) -> String {
    let text = format!("{x:.decimals$}");
    let whole = text.find('.').unwrap_or(text.len());
    let mut out = String::new();
    for (i, c) in text.chars().enumerate() {
        if i > 0 && i < whole && (whole - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    out
}

fn main() {
    for (name, seconds) in PERIODS {
        println!("1 {name:<13} = {:>10} s", grouped(seconds as f64, 0));
    }

    println!();
    println!("{:>16}  {:>18}", "Events a day", "average per second");
    for per_day in DAILY_COUNTS {
        let rate = per_day as f64 / DAY as f64;
        println!(
            "{:>16}  {:>18}",
            grouped(per_day as f64, 0),
            grouped(rate, 1)
        );
    }

    println!();
    let monthly: u64 = 3_000_000_000; // an example: 3 billion events in a 30-day month
    let rate = monthly as f64 / MONTH as f64;
    println!(
        "3 billion a month = {} per second on average",
        grouped(rate, 0)
    );
    // Dividing one whole number by another in integer arithmetic drops the fraction.
    let truncated = 1_000_000 / DAY;
    println!("1,000,000 a day in integer division: {truncated} per second, not 11.6");
}

In Rust: / on u64 values is integer division, so each rate converts with as f64 first; {x:.decimals$} takes the number of decimals from a variable.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const MONTH = 30 * DAY;
const YEAR = 365 * DAY;

const PERIODS: readonly (readonly [string, number])[] = [
  ["minute", MINUTE],
  ["hour", HOUR],
  ["day", DAY],
  ["30-day month", MONTH],
  ["365-day year", YEAR],
];
const DAILY_COUNTS = [1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000];

// x rounded to the given decimals, with commas between groups of three digits.
function grouped(x: number, decimals = 0): string {
  const parts = x.toFixed(decimals).split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+$)/g, ",");
  return parts.join(".");
}

for (const [name, seconds] of PERIODS) {
  console.log(`1 ${name.padEnd(13)} = ${grouped(seconds).padStart(10)} s`);
}

console.log();
console.log(`${"Events a day".padStart(16)}  ${"average per second".padStart(18)}`);
for (const perDay of DAILY_COUNTS) {
  console.log(`${grouped(perDay).padStart(16)}  ${grouped(perDay / DAY, 1).padStart(18)}`);
}

console.log();
const monthly = 3_000_000_000; // an example: 3 billion events in a 30-day month
console.log(`3 billion a month = ${grouped(monthly / MONTH)} per second on average`);
// Dividing one whole number by another in integer arithmetic drops the fraction.
const truncated = Math.trunc(1_000_000 / DAY);
console.log(`1,000,000 a day in integer division: ${truncated} per second, not 11.6`);

In TypeScript: Number is a single double type, so / keeps the fraction and Math.trunc gives the integer division, as in JavaScript.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

const (
	minute = 60
	hour   = 60 * minute
	day    = 24 * hour
	month  = 30 * day
	year   = 365 * day
)

// grouped rounds x to the given decimals and puts commas between groups of three digits.
func grouped(x float64, decimals int) string {
	text := strconv.FormatFloat(x, 'f', decimals, 64)
	whole := strings.IndexByte(text, '.')
	if whole < 0 {
		whole = len(text)
	}
	var b strings.Builder
	for i, c := range text {
		if i > 0 && i < whole && (whole-i)%3 == 0 {
			b.WriteByte(',')
		}
		b.WriteRune(c)
	}
	return b.String()
}

func main() {
	periods := []struct {
		name    string
		seconds int64
	}{
		{"minute", minute},
		{"hour", hour},
		{"day", day},
		{"30-day month", month},
		{"365-day year", year},
	}
	dailyCounts := []int64{1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000}

	for _, p := range periods {
		fmt.Printf("1 %-13s = %10s s\n", p.name, grouped(float64(p.seconds), 0))
	}

	fmt.Println()
	fmt.Printf("%16s  %18s\n", "Events a day", "average per second")
	for _, perDay := range dailyCounts {
		rate := float64(perDay) / day
		fmt.Printf("%16s  %18s\n", grouped(float64(perDay), 0), grouped(rate, 1))
	}

	fmt.Println()
	var monthly int64 = 3_000_000_000 // an example: 3 billion events in a 30-day month
	fmt.Printf("3 billion a month = %s per second on average\n", grouped(float64(monthly)/month, 0))
	// Dividing one whole number by another in integer arithmetic drops the fraction.
	truncated := 1_000_000 / day
	fmt.Printf("1,000,000 a day in integer division: %d per second, not 11.6\n", truncated)
}

In Go: The constants are untyped, so 1_000_000 / day is an integer division the compiler does, while float64(perDay) / day divides as floating point.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
let minute: Int64 = 60
let hour = 60 * minute
let day = 24 * hour
let month = 30 * day
let year = 365 * day

let periods: [(name: String, seconds: Int64)] = [
  ("minute", minute), ("hour", hour), ("day", day), ("30-day month", month),
  ("365-day year", year),
]
let dailyCounts: [Int64] = [1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000]

// Padding by hand: without Foundation the standard library has no String(format:).
func padLeft(_ text: String, to width: Int) -> String {
  String(repeating: " ", count: max(0, width - text.count)) + text
}

func padRight(_ text: String, to width: Int) -> String {
  text + String(repeating: " ", count: max(0, width - text.count))
}

/// x rounded to the given decimals, with commas between groups of three digits.
func grouped(_ x: Double, decimals: Int = 0) -> String {
  var scale: Int64 = 1
  for _ in 0..<decimals { scale *= 10 }
  let scaled = Int64((x * Double(scale)).rounded())
  let whole = Array(String(scaled / scale))
  var out = ""
  for (i, digit) in whole.enumerated() {
    if i > 0 && (whole.count - i) % 3 == 0 {
      out.append(",")
    }
    out.append(digit)
  }
  guard decimals > 0 else { return out }
  let fraction = String(scaled % scale)
  return out + "." + String(repeating: "0", count: decimals - fraction.count) + fraction
}

for (name, seconds) in periods {
  print("1 \(padRight(name, to: 13)) = \(padLeft(grouped(Double(seconds)), to: 10)) s")
}

print()
print("\(padLeft("Events a day", to: 16))  \(padLeft("average per second", to: 18))")
for perDay in dailyCounts {
  let rate = Double(perDay) / Double(day)
  print(
    "\(padLeft(grouped(Double(perDay)), to: 16))  \(padLeft(grouped(rate, decimals: 1), to: 18))")
}

print()
let monthly: Int64 = 3_000_000_000  // an example: 3 billion events in a 30-day month
print("3 billion a month = \(grouped(Double(monthly) / Double(month))) per second on average")
// Dividing one whole number by another in integer arithmetic drops the fraction.
let truncated = 1_000_000 / day
print("1,000,000 a day in integer division: \(truncated) per second, not 11.6")

In Swift: Int64 holds 10,000,000,000 in the WebAssembly build too, where Int has 32 bits, and / between two Int64 values drops the fraction.

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

# Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
# and daily counts as average rates per second.
MINUTE = 60
HOUR = 60 * MINUTE
DAY = 24 * HOUR
MONTH = 30 * DAY
YEAR = 365 * DAY

PERIODS = {
  'minute' => MINUTE, 'hour' => HOUR, 'day' => DAY, '30-day month' => MONTH, '365-day year' => YEAR
}.freeze
DAILY_COUNTS = [1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000].freeze

# x rounded to the given decimals, with commas between groups of three digits.
def grouped(value, decimals = 0)
  whole, fraction = format("%.#{decimals}f", value).split('.')
  [whole.gsub(/\B(?=(\d{3})+$)/, ','), fraction].compact.join('.')
end

PERIODS.each do |name, seconds|
  puts "1 #{name.ljust(13)} = #{grouped(seconds).rjust(10)} s"
end

puts
puts "#{'Events a day'.rjust(16)}  #{'average per second'.rjust(18)}"
DAILY_COUNTS.each do |per_day|
  puts "#{grouped(per_day).rjust(16)}  #{grouped(per_day.fdiv(DAY), 1).rjust(18)}"
end

puts
monthly = 3_000_000_000 # an example: 3 billion events in a 30-day month
puts "3 billion a month = #{grouped(monthly.fdiv(MONTH))} per second on average"
# Dividing one whole number by another in integer arithmetic drops the fraction.
truncated = 1_000_000 / DAY
puts "1,000,000 a day in integer division: #{truncated} per second, not 11.6"

In Ruby: / between two Integers drops the fraction, so the rates use fdiv, which divides as floating point.

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.roundToLong

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
const val MINUTE = 60L
const val HOUR = 60 * MINUTE
const val DAY = 24 * HOUR
const val MONTH = 30 * DAY
const val YEAR = 365 * DAY

val periods =
    listOf(
        "minute" to MINUTE,
        "hour" to HOUR,
        "day" to DAY,
        "30-day month" to MONTH,
        "365-day year" to YEAR,
    )
val dailyCounts = longArrayOf(1_000_000, 10_000_000, 100_000_000, 1_000_000_000, 10_000_000_000)

// This number rounded to the given decimals, with commas between groups of three digits.
fun Double.grouped(decimals: Int = 0): String {
    var scale = 1L
    repeat(decimals) { scale *= 10 }
    val scaled = (this * scale).roundToLong()
    val whole =
        (scaled / scale)
            .toString()
            .reversed()
            .chunked(3)
            .joinToString(",")
            .reversed()
    val fraction = (scaled % scale).toString().padStart(decimals, '0')
    return if (decimals == 0) whole else "$whole.$fraction"
}

fun main() {
    for ((name, seconds) in periods) {
        println("1 ${name.padEnd(13)} = ${seconds.toDouble().grouped().padStart(10)} s")
    }

    println()
    println("${"Events a day".padStart(16)}  ${"average per second".padStart(18)}")
    for (perDay in dailyCounts) {
        val rate = perDay.toDouble() / DAY
        println("${perDay.toDouble().grouped().padStart(16)}  ${rate.grouped(1).padStart(18)}")
    }

    println()
    val monthly = 3_000_000_000L // an example: 3 billion events in a 30-day month
    println("3 billion a month = ${(monthly.toDouble() / MONTH).grouped()} per second on average")
    // Dividing one whole number by another in integer arithmetic drops the fraction.
    val truncated = 1_000_000 / DAY
    println("1,000,000 a day in integer division: $truncated per second, not 11.6")
}

In Kotlin: / between two Longs drops the fraction, so each rate converts the count to Double first. The common standard library has no String.format, so grouped scales by ten per decimal, rounds to a Long and puts the point back.

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

// Seconds in the periods that estimates use (a month taken as 30 days, a year as 365),
// and daily counts as average rates per second.
const minute = 60;
const hour = 60 * minute;
const day = 24 * hour;
const month = 30 * day;
const year = 365 * day;

const periods = [
  ('minute', minute),
  ('hour', hour),
  ('day', day),
  ('30-day month', month),
  ('365-day year', year),
];
const dailyCounts = [
  1_000_000,
  10_000_000,
  100_000_000,
  1_000_000_000,
  10_000_000_000,
];

/// x rounded to the given decimals, with commas between groups of three digits.
String grouped(num x, [int decimals = 0]) {
  final parts = x.toStringAsFixed(decimals).split('.');
  parts[0] = parts[0].replaceAll(RegExp(r'\B(?=(\d{3})+$)'), ',');
  return parts.join('.');
}

void main() {
  for (final (name, seconds) in periods) {
    print('1 ${name.padRight(13)} = ${grouped(seconds).padLeft(10)} s');
  }

  print('');
  print('${'Events a day'.padLeft(16)}  ${'average per second'.padLeft(18)}');
  for (final perDay in dailyCounts) {
    final rate = perDay / day;
    print('${grouped(perDay).padLeft(16)}  ${grouped(rate, 1).padLeft(18)}');
  }

  print('');
  const monthly =
      3_000_000_000; // an example: 3 billion events in a 30-day month
  print(
    '3 billion a month = ${grouped(monthly / month)} per second on average',
  );
  // Dividing one whole number by another in integer arithmetic drops the fraction.
  const truncated = 1_000_000 ~/ day;
  print('1,000,000 a day in integer division: $truncated per second, not 11.6');
}

In Dart: / always returns a double and ~/ is the integer division, like Python's / and //; toStringAsFixed rounds before the commas go in.

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

1 minute        =         60 s
1 hour          =      3,600 s
1 day           =     86,400 s
1 30-day month  =  2,592,000 s
1 365-day year  = 31,536,000 s

    Events a day  average per second
       1,000,000                11.6
      10,000,000               115.7
     100,000,000             1,157.4
   1,000,000,000            11,574.1
  10,000,000,000           115,740.7

3 billion a month = 1,157 per second on average
1,000,000 a day in integer division: 11 per second, not 11.6

Two shortcuts are worth remembering: a million events a day is about 12 a second, and a billion a day about 11,600 a second. For a 30-day month divide by about 2.6 million, and for a year by about 31.5 million. Every one of these is an average over the whole period. Real traffic is never flat; the lesson on estimating traffic turns an average into a peak.

Integer division drops the fraction

The program’s last line shows a slip that compiles without a warning. In Java, C, C++, C#, Go, Rust, Swift, Kotlin and Ruby, dividing one integer by another keeps only the whole part, so 1,000,000 a day becomes 11 a second instead of 11.6, and any count under 86,400 a day becomes 0. Python’s / always keeps the fraction and its // drops it (Python reference). Divide in floating point: convert the count first, or use a division that keeps the fraction, as every version of the program does for its rates.

Checkpoint

Check: From a daily count to a rate

  1. Question 1 of 2 A service handles 500 million requests in a 30-day month. About how many is that per second, on average?

    Type a number.

    A hint

    A 30-day month has 2,592,000 seconds.

    Show the answer: Question 1 of 2

    Answer: 193 requests a second (anything from 189 to 197 counts)

    500,000,000 ÷ 2,592,000 ≈ 193 a second. It is an average over the whole month, nights and weekends included, so the busiest hours bring more.

  2. Question 2 of 2 In Java, Go or Rust, a daily count of 1,000,000 held in an integer is divided by the integer 86,400. What is the result?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 11

    Every version of the lesson's program prints 11 on its last line. Convert the count to a floating-point number before dividing, as the programs do for their rates, and the result is 11.6.

Round on purpose, and say which way

State an estimate with one or two significant figures: The digits of a number that carry meaning, counted from its first digit that is not zero. Rounded to two significant figures, 17,361 becomes 17,000.: “about 17,000 requests a second” is honest, while 17,361 claims a precision that the assumptions behind it do not have. Every rounding pushes the result one way, though, so round on purpose and say which way it went.

The same estimate, rounded three ways Python · units/rounding.py
import math

DAY = 86_400


def sig(x, digits=2):
    """x rounded to `digits` significant figures."""
    if x == 0:
        return 0
    places = digits - 1 - math.floor(math.log10(abs(x)))
    value = round(x, places)
    return int(value) if places <= 0 else value


per_day = 1.5 * 10**9  # an estimate: 1.5 billion requests a day

exact = per_day / DAY
rounded_day = per_day / 10**5  # treating a day as 100,000 seconds

print(f"Exact:                  {exact:,.0f} per second")
print(f"Day taken as 10^5 s:    {rounded_day:,.0f} per second ({(rounded_day / exact - 1) * 100:+.1f}%)")
print(f"Two significant digits: {sig(exact):,} per second")
print()
# Every rounding pushes an estimate one way or the other: say which.
for label, value in [("Day rounded up to 10^5 s", rounded_day), ("Day rounded down to 8 x 10^4 s", per_day / (8 * 10**4))]:
    direction = "under" if value < exact else "over"
    print(f"{label:<31} {value:>7,.0f}/s  {direction}estimates the load")

Output

Exact:                  17,361 per second
Day taken as 10^5 s:    15,000 per second (-13.6%)
Two significant digits: 17,000 per second

Day rounded up to 10^5 s         15,000/s  underestimates the load
Day rounded down to 8 x 10^4 s   18,750/s  overestimates the load

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 rounding.py

Dividing by 10510^{5} instead of 86,400 is tempting because it is easy, but every rate comes out about 14% too low (the true rate is about 16% higher than the shortcut’s). When you size capacity, that is the unsafe direction: you would plan for less load than will arrive. When the question is how much load a system must carry, round so that the load comes out higher; when it is how long a resource will last, round so that the time comes out shorter. If you do take a shortcut, say so: “about 15,000 a second, a little low because I used 10510^{5} seconds a day”.

The same rule, for the three questions an estimate usually answers:

The question Round so that The danger on the other side
How much load must it carry? The load comes out higher Too few servers for the traffic that arrives
How much storage will it need? The size comes out larger A disk or a quota full before the plan said
How long will a resource last? The time comes out shorter An ID space, a disk or a budget used up early

Lakh and crore

Indian figures are often written in lakh (1,00,000, which is 10510^{5}) and crore (1,00,00,000, which is 10710^{7}), with commas that keep the last three digits together and split the digits before them into pairs (NCERT, class 7 mathematics). The Reserve Bank of India’s Payment System Indicators give monthly payment volumes, including UPI’s, in lakh, so converting lakh is the first step of any check against those tables. Python accepts an underscore between any two digits of a number (Python reference), so a figure can be typed in the grouping it was printed in:

A volume in lakh as a rate per second Python · units/lakh_crore.py
LAKH = 10**5
CRORE = 10**7
DAY = 86_400

# Python accepts _ between digits, so Indian digit grouping can be written as it is printed.
monthly = 2_45_089.58 * LAKH  # a monthly volume given in lakh
print(f"2,45,089.58 lakh = {monthly:,.0f} = {monthly:.2e}")
print(f"Spread over a 31-day month: {monthly / (31 * DAY):,.0f} per second")
print(f"1 crore a day = {CRORE / DAY:,.1f} per second")

Output

2,45,089.58 lakh = 24,508,958,000 = 2.45e+10
Spread over a 31-day month: 9,151 per second
1 crore a day = 115.7 per second

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 lakh_crore.py

Lakh Crore Converter (to Million, Billion) Convert lakh and crore to millions and billions, and back.

Checkpoint

Check: Rounding on purpose

  1. Question 1 of 2 To save time you divide a monthly count by 3,000,000 seconds instead of the 2,592,000 of a 30-day month. Which way does the rate move?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: It comes out about 14 % too low, so a capacity plan built on it is short

    Dividing by too many seconds makes the load look smaller than it is, the unsafe direction when you size capacity. Use the real number, or say that your figure is a little low.

  2. Question 2 of 2 An estimate works out at 23,148 requests a second. How should you say it?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: About 23,000 a second

    Keep one or two significant figures and say which way any shortcut pushed the result. 23,148 to two significant figures is 23,000.

Four slips to check before you say a number

Each of these slips gives no error message, only a number that is wrong by a factor you can name:

Slip What it does, and the check
Bits for bytes A “Gb” is a gigabit. Divide a link rate by 8 before comparing it with a file size, or the copy looks eight times faster than it can be.
Binary for decimal A GiB is 7.4% more than a GB, and a TiB 10% more than a TB. Say which one you mean.
The wrong period Per minute and per second differ by 60 times. Even month lengths matter a little: a 31-day month has 3.3% more seconds than a 30-day one.
An average taken for a peak A daily count divided by 86,400 is the average rate. The busiest hour always brings at least that much, and usually far more.
Data Storage Converter Check a decimal or binary size conversion to the byte. Data Rate Converter (Mbps to MB/s) Turn link rates in bits per second into bytes per second, and back. Time Unit Converter Convert days, months and years into seconds when a requirement uses an unusual period.

Checkpoint

Check: Checking a number before you say it

  1. One question An estimate reads: "2 billion requests a day ÷ 86,400 ≈ 23,000 a second, so a database that serves 25,000 queries a second has headroom." What is wrong with it?

    Choose one answer.

    Show the answer: One question

    Answer: It sizes the database for the average, and the busiest hour brings more

    A daily count divided by 86,400 is the average rate, the lowest load the busiest hour will bring. Size for a peak with a stated window; the lesson on estimating traffic shows where the factor comes from.

Practise: convert sizes and rates

Write the two converters an estimate sheet leans on: sizes in decimal and binary units to bytes, and counts per period to an average rate per second. Its sample tests run on this page; open the first hint if a failing test leaves you guessing why:

Exercise · Easy · Python

Convert sizes to bytes and counts to rates

Write two small converters that an estimate sheet can lean on, in conversions.py.

to_bytes(amount, unit) returns how many bytes amount of unit is.

  • Decimal units are powers of ten: "B", "kB", "MB", "GB", "TB" and "PB", so to_bytes(2, "kB") is 2000.
  • Binary units are powers of two: "KiB", "MiB", "GiB", "TiB" and "PiB", so to_bytes(2, "KiB") is 2048.
  • Any other unit raises ValueError. That includes "Gb", which means gigabits: a converter that guessed would be off by a factor of eight.

per_second(count, period) returns the average number of events per second when count events happen in one period: "minute", "hour", "day", "month" (taken as 30 days) or "year" (taken as 365 days). For example, per_second(86_400, "day") is 1.0. Any other period raises ValueError.

The sample tests import both functions from conversions.py, check whole-number results exactly and check rates to nine significant figures.

Starter code · conversions.py

def to_bytes(amount, unit):
    """Return the number of bytes in `amount` of `unit` ("kB", "MiB" ...); raise ValueError for other units."""
    # Replace this line with your code.
    return 0


def per_second(count, period):
    """Return the average events per second for `count` events per `period` ("minute" ... "year")."""
    # Replace this line with your code.
    return 0
The sample tests · test_conversions.py
import math

from conversions import per_second, to_bytes


def raises_value_error(function, *args):
    """True when function(*args) raises ValueError."""
    try:
        function(*args)
    except ValueError:
        return True
    return False


def test_decimal_units():
    """converts decimal units with powers of ten"""
    assert to_bytes(5, "B") == 5
    assert to_bytes(1, "kB") == 1_000
    assert to_bytes(3, "GB") == 3_000_000_000
    assert to_bytes(2, "TB") == 2 * 10**12
    assert to_bytes(1.5, "MB") == 1_500_000


def test_binary_units():
    """converts binary units with powers of two"""
    assert to_bytes(1, "KiB") == 1_024
    assert to_bytes(1, "GiB") == 1_073_741_824
    assert to_bytes(4, "TiB") == 4 * 2**40


def test_unknown_unit():
    """refuses units it does not know, such as gigabits"""
    assert raises_value_error(to_bytes, 1, "Gb")
    assert raises_value_error(to_bytes, 1, "gigabyte")


def test_per_day():
    """turns a daily count into an average per second"""
    assert per_second(86_400, "day") == 1
    assert math.isclose(per_second(10**9, "day"), 11_574.074074, rel_tol=1e-9)


def test_other_periods():
    """knows minutes, hours, 30-day months and 365-day years"""
    assert per_second(60, "minute") == 1
    assert per_second(7_200, "hour") == 2
    assert per_second(2_592_000, "month") == 1
    assert math.isclose(per_second(3 * 10**9, "month"), 1_157.407407, rel_tol=1e-9)
    assert per_second(31_536_000, "year") == 1


def test_unknown_period():
    """refuses periods it does not know"""
    assert raises_value_error(per_second, 10, "fortnight")
A hint

Keep one dictionary from unit name to the number of bytes in one unit ("kB": 10**3, "KiB": 2**10 …) and one from period name to its length in seconds. Then each function is a lookup and one multiplication or division, and if unit not in factors: raise ValueError(...) handles the units you do not know.

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.

After that, practise the conversions themselves. Each question explains its answer at once, and the next one aims at whichever idea you got wrong:

Practice that adapts to you

Practise this lesson

14 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 14 A drive is sold as 2 TB, in decimal units. How many GiB does it hold?

    Type a number.

    A hint

    1 GiB is 2³⁰ = 1,073,741,824 bytes.

    Show the answer: Question 1 of 14

    Answer: 1862.6 GiB (anything from 1825.6 to 1899.6 counts)

    2 TB is 2 × 10^12 bytes and 1 GiB is 2^30 = 1,073,741,824 bytes, so the drive holds 2 × 10^12 / 2^30 ≈ 1,862.6 GiB. Nothing is missing: the same bytes are counted in a bigger unit.

  2. Question 2 of 14 Which of these units are powers of two?

    Choose every answer that is right.

    Show the answer: Question 2 of 14

    Answer:

    • KiB
    • TiB
    • GiB

    The IEC prefixes with an "i" (kibi, gibi, tebi) are powers of two. kB is 1,000 bytes, and Gbit/s is a decimal rate of 10^9 bits a second.

  3. Question 3 of 14 What does this program print?

    What does this program print? Choose one answer.

    disk_bytes = 500 * 10**9  # a drive sold as "500 GB" (decimal units)
    print(round(disk_bytes / 2**30, 1), "GiB")
    Show the answer: Question 3 of 14

    Answer: it prints

    465.7 GiB

    500 × 10^9 bytes divided by 2^30 bytes per GiB is about 465.66, rounded to 465.7. A drive sold in decimal gigabytes always shows fewer binary gibibytes.

  4. Question 4 of 14 A monitoring tool shows a volume of 2.0 TiB, while the capacity plan lists the volume at 2.2 TB. Are these the same volume?

    Choose one answer.

    Show the answer: Question 4 of 14

    Answer: Yes, because 2 TiB is about 2.2 × 10¹² bytes

    Convert to bytes and compare: 2 TiB = 2 × 2⁴⁰ ≈ 2.2 × 10¹² bytes = 2.2 TB. Mixed units on two dashboards are a common source of false alarms and of disks that fill up unexpectedly.

  5. Question 5 of 14 A link is rated at 100 Mbit/s. At most how fast can it copy a file?
    Show the answer: Question 5 of 14

    Answer: 12.5 MB/s

    A byte is 8 bits, so 100 million bits a second is at most 12.5 million bytes a second. Headers and other traffic make a real copy slower still.

  6. Question 6 of 14 A nightly backup of 6 TB must cross a 1 Gbit/s link within a 4-hour window. What do you tell the team?

    Choose one answer.

    Show the answer: Question 6 of 14

    Answer: It cannot fit even at full speed, so the plan needs a faster link, a smaller copy or a longer window

    Divide the link rate by 8 first: 1 Gbit/s is 125 MB/s, and 6 TB ÷ 125 MB/s = 48,000 s ≈ 13.3 hours. When even the lower bound misses the window, no tuning rescues the plan.

  7. Question 7 of 14 About how large is 2³⁰?

    Choose one answer.

    Show the answer: Question 7 of 14

    Answer: About a billion

    Ten doublings make about a thousand, because 2¹⁰ = 1,024, so 2²⁰ is about a million, 2³⁰ about a billion and 2⁴⁰ about a trillion.

  8. Question 8 of 14 A signed 32-bit ID column tops out at 2,147,483,647. A table that receives 500 inserts a second uses it up after about how many days?

    Type a number.

    A hint

    Divide by the inserts a second, then by the seconds in a day.

    Show the answer: Question 8 of 14

    Answer: 49.7 days (anything from 48.7 to 50.7 counts)

    2,147,483,647 ÷ 500 ÷ 86,400 ≈ 49.7 days. A signed type has half the values of an unsigned one, so at half the rate it runs out as fast as the program's unsigned counter at 1,000 a second.

  9. Question 9 of 14 About how many events a second, on average, is a billion events a day?

    Type a number.

    Show the answer: Question 9 of 14

    Answer: 11574 events a second (anything from 11374 to 11774 counts)

    1,000,000,000 ÷ 86,400 ≈ 11,574, about 11,600 a second. A million a day is about 12 a second, so each factor of a thousand in the daily count is a factor of a thousand in the rate.

  10. Question 10 of 14 A service receives 300 million requests a day. About how many is that per second, on average?

    Type a number.

    Show the answer: Question 10 of 14

    Answer: 3472.2 requests per second (anything from 3402.2 to 3542.2 counts)

    300,000,000 / 86,400 ≈ 3,472 requests a second. That is the average over the whole day; the busiest hour brings more.

  11. Question 11 of 14 To save time you divide a daily count by 100,000 instead of 86,400. What happens to the rate?

    Choose one answer.

    Show the answer: Question 11 of 14

    Answer: It comes out about 14% too low, so a plan based on it underestimates the load

    86,400 / 100,000 = 0.864, so every rate is multiplied by 0.864, about 14% too low. For capacity planning that is the unsafe direction, so either use 86,400 or say that your figure is a little low.

  12. Question 12 of 14 Logs grow by about 120 GB a day and a 10 TB disk holds them. You estimate how long the disk lasts. Which shortcut is safe?

    Choose one answer.

    Show the answer: Question 12 of 14

    Answer: Round the daily growth up, to 150 GB, so the days come out fewer

    10 TB ÷ 120 GB a day ≈ 83 days. Rounding the growth up to 150 GB gives about 67 days, a shorter time, which is the safe direction when the question is how long something lasts.

  13. Question 13 of 14 A plan says: "A 1 Gbit/s link moves a 100 GB dataset in 100 seconds." Which slip is it?

    Choose one answer.

    Show the answer: Question 13 of 14

    Answer: Bits taken for bytes

    A "Gb" is a gigabit. Divide a link rate by 8 before comparing it with a size in bytes: 100 GB ÷ 125 MB/s = 800 s.

  14. Question 14 of 14 A monitoring graph shows "requests: 6,000" for each one-minute point, and a teammate sizes the servers for 6,000 requests a second. What do you check first?

    Choose one answer.

    Show the answer: Question 14 of 14

    Answer: The period of the graph's points, because 6,000 a minute is only 100 a second

    Write the period beside every rate. 6,000 a minute is 6,000 ÷ 60 = 100 a second, so the servers would have been sized for 60 times the load.

Interview questions

Warm-up (fresher): why does a drive sold as 1 TB show up as about 931 GB in some tools, and which units should a capacity estimate use?

The drive maker counts in SI units, where tera means 10¹², so 1 TB is 1,000,000,000,000 bytes. A tool that divides those bytes by 2³⁰, a gibibyte, gets 931.3 and often keeps the label GB, so the drive seems to have lost 69 GB. Nothing is missing: the same bytes are counted in a unit 7.4 % bigger. In an estimate, pick one family and say which. Decimal units are easy to multiply in your head and are what drives, links and most published figures use; binary units suit what is counted in binary, such as memory, page sizes and limits documented in KiB or MiB. At tera the two differ by 10 %, often less than the uncertainty in the assumptions, but enough to matter for a disk that is nearly full.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    An events table uses a signed 32-bit auto-increment ID and takes about 400 inserts a second on average, 2,000 at its daily peak. How long until the IDs run out, what fails when they do, and what would you change?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    A nightly job must copy 40 TB of logs to another data centre over a 10 Gbit/s link within an 8-hour window. Will it fit? What do you tell the team, and what are the options if it does not?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • SI prefixes (kB, MB, GB) are powers of ten; IEC prefixes (KiB, MiB, GiB) are powers of two. They differ by 2.4% at kilo and 10% at tera, so pick one family and say which.
  • Links are rated in bits per second and data is counted in bytes: divide by 8.
  • 210≈1032^{10} \approx 10^{3}, and the sizes of 32-bit and 64-bit integers decide how long an ID space lasts.
  • Divide a daily count by 86,400 to get the average rate per second; a million a day is about 12 a second.
  • Keep one or two significant figures, and round in the direction that keeps the answer safe.
  • Before you say a number, check bits against bytes, binary against decimal units, the period, and whether it is an average or a peak.

Terms in this lesson

binary prefix (IEC)
A prefix for a power of two: kibi (Ki) is 2¹⁰ = 1,024, mebi (Mi) 2²⁰, gibi (Gi) 2³⁰ and tebi (Ti) 2⁴⁰. A gibibyte is 1,073,741,824 bytes, 7.4 % more than a gigabyte.
ID space
All the values an identifier can take. A 32-bit counter has 2³² = 4,294,967,296 of them; once they are used up, new records need a wider type or another scheme.
SI prefix
A prefix that multiplies a unit by a power of ten: kilo (k) is 10³, mega (M) 10⁶, giga (G) 10⁹ and tera (T) 10¹², so a kilobyte is 1,000 bytes and a gigabyte 10⁹ bytes.
significant figures
The digits of a number that carry meaning, counted from its first digit that is not zero. Rounded to two significant figures, 17,361 becomes 17,000.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.