Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 1

Sanity-checking a store choice at target scale

Check a PostgreSQL choice for an append-only dataset against three years of growth: size per node, write rate, restore time and cache, with best, expected and worst cases; measure bytes per row and watch the decision move; then test partition keys for hot spots.

Contentsand lesson path

What you will learn

  • Check a store choice against target scale: data size per node, write throughput, partition-key hot spots and the point at which the data must be partitioned.

01. The problem

In lesson 2 the parcel service kept its scan events in PostgreSQL, the engine the team already runs, on a primary of their own, and promised to revisit the choice if a scale check showed a limit within 18 months. This lesson is that check: can scan events stay on one PostgreSQL primary for three years, and if not, when must the data be partitioned, and by which key?

"Partitioned" has two meanings that are easy to mix up. Table partitioning splits one table into child tables on the same server, for example one per month. It makes dropping old data cheap but adds no capacity. Sharding places partitions on different servers, which adds capacity but turns some queries into calls to several servers.

02. Step 1: write the inputs and the limits

Every input gets a unit, best/expected/worst values where we are unsure, and a basis; so does every limit of the node, because a limit nobody can explain cannot be defended in a review.

Assumptions · scan events on one PostgreSQL primary
input                          best      expected   worst     basis
parcels per day, year 1        1.2 M     2.0 M      3.0 M     sales forecast
scans per parcel               6         8          10        depot process
volume growth per year         20%       35%        50%       sales forecast
peak hour / average hour       2.5       3          4         shift pattern
bytes per row, with indexes    100 (first guess, step 3 measures it)
days kept online               400, then exported to the archive
hot data for the tracking page the last 7 days
other data on this node        none: scan events get their own primary (step 4 tests it)

limit of one node              value     basis
data on disk                   2.4 TB    60% of a 4 TB volume
restorable within the RTO      1.6 TB    4 h x 400 GB/h from a timed restore
writes at peak                 6,000/s   load test with both indexes
cache for hot pages            64 GB     half of 128 GB RAM

Two of the limits are not about hardware. The disk limit stops at 60% of the volume, leaving room for the write-ahead log, vacuum and index rebuilds. The restore limit comes from the recovery time objective on the card: if a full restore must finish within 4 hours and a timed test restored 400 GB per hour, the node may hold at most 1.6 TB. PostgreSQL's own hard limit, 32 TB per table with 8 kB blocks, is far away: operational limits like these usually bind first. All four are limits of the whole node, so the tables below assume that scan events have it to themselves; step 4 tests that assumption.

03. Step 2: compute every dimension for every scenario

The script applies the growth rate for each year and reports what share of each limit is used. To stay safe, it treats each year's daily volume as if it had lasted all 400 days online, which slightly overstates the size while volume grows. Save it as scan_capacity.py. It takes three optional arguments, bytes per row, days online and terabytes of other data on the node, so that we can rerun it when an input changes.

Python · scan_capacity.py
"""Can scan events stay on one PostgreSQL primary for three years? (Python 3.12)"""
import sys

DAY_S = 86_400
GB, TB = 10**9, 10**12

# Every input is an assumption; units are in the names.
SCENARIOS = {
    "best": {"parcels_per_day": 1_200_000, "scans_per_parcel": 6,
             "growth_per_year": 0.20, "peak_factor": 2.5},
    "expected": {"parcels_per_day": 2_000_000, "scans_per_parcel": 8,
                 "growth_per_year": 0.35, "peak_factor": 3.0},
    "worst": {"parcels_per_day": 3_000_000, "scans_per_parcel": 10,
              "growth_per_year": 0.50, "peak_factor": 4.0},
}
BYTES_PER_ROW = float(sys.argv[1]) if len(sys.argv) > 1 else 100.0  # rows + indexes
RETENTION_DAYS = int(sys.argv[2]) if len(sys.argv) > 2 else 400  # online days
OTHER_TB = float(sys.argv[3]) if len(sys.argv) > 3 else 0.0  # other data on this node
HOT_DAYS = 7  # the tracking page mostly reads the last week

# What one node may hold or absorb. Each limit comes from a policy or a test.
LIMITS = {
    "disk": 2.4,  # TB of data: 60% of a 4 TB volume, room for WAL, vacuum, rebuilds
    "restore": 1.6,  # TB restorable in the 4-hour target at a timed 400 GB/hour
    "writes": 6_000,  # rows/s at peak: load test with both indexes, p99 on target
    "cache": 64,  # GB: half of the node's 128 GB RAM for hot pages
}


def load(s: dict, year: int) -> dict:
    rows_day = (s["parcels_per_day"] * s["scans_per_parcel"]
                * (1 + s["growth_per_year"]) ** (year - 1))
    online_tb = rows_day * BYTES_PER_ROW * RETENTION_DAYS / TB
    return {
        "rows_day": rows_day,
        "online": online_tb,  # scan events only
        "disk": online_tb + OTHER_TB,  # every byte on the node counts
        "restore": online_tb + OTHER_TB,
        "writes": rows_day / DAY_S * s["peak_factor"],
        "cache": rows_day * BYTES_PER_ROW * HOT_DAYS / GB,
    }


print(f"{BYTES_PER_ROW:.0f} bytes per row, {RETENTION_DAYS} days online, "
      f"{OTHER_TB} TB of other data   (share of each limit used)")
print(f"{'scenario':<9}{'year':>5}{'rows/day':>10}{'online TB':>11}"
      + "".join(f"{k:>9}" for k in LIMITS))
for name, s in SCENARIOS.items():
    for year in (1, 2, 3):
        x = load(s, year)
        use = [x[k] / LIMITS[k] for k in LIMITS]
        flag = "  <- over" if max(use) > 1 else ""
        print(f"{name:<9}{year:>5}{x['rows_day'] / 1e6:>9.1f}M{x['online']:>11.2f}"
              + "".join(f"{u:>9.0%}" for u in use) + flag)
Terminal
python3.12 scan_capacity.py
Expected output
100 bytes per row, 400 days online, 0.0 TB of other data   (share of each limit used)
scenario  year  rows/day  online TB     disk  restore   writes    cache
best         1      7.2M       0.29      12%      18%       3%       8%
best         2      8.6M       0.35      14%      22%       4%       9%
best         3     10.4M       0.41      17%      26%       5%      11%
expected     1     16.0M       0.64      27%      40%       9%      18%
expected     2     21.6M       0.86      36%      54%      12%      24%
expected     3     29.2M       1.17      49%      73%      17%      32%
worst        1     30.0M       1.20      50%      75%      23%      33%
worst        2     45.0M       1.80      75%     112%      35%      49%  <- over
worst        3     67.5M       2.70     113%     169%      52%      74%  <- over

Writes never pass 52% of the tested limit, so this dataset is not write-bound, however write-heavy "scan events" sounds, and the cache share stays below three quarters. The restore limit binds first in every scenario, because it applies to the same online size as the disk limit but is lower. With the first guess of 100 bytes per row, the expected case stays within limits for three years, and the worst case crosses in year 2.

04. Step 3: replace the weakest guess with a measurement

Which input deserves a measurement first? The one that moves the result most and is least certain. Bytes per row multiplies every size, and 100 bytes was a guess: the columns hold about 46 bytes of values (three 8-byte numbers, two 4-byte numbers, a 2-byte status and a short location text), plus a rough allowance for indexes.

The script below creates the real table and indexes in PostgreSQL 18 and loads one million synthetic rows that mimic the real ones: 125,000 parcels with 8 scans each, arriving in mixed order. Save it as size_check.sql.

SQL · size_check.sql
-- Measure bytes per scan event in PostgreSQL: one million synthetic rows.
CREATE TABLE scan_events (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  parcel_id bigint NOT NULL,
  scanned_at timestamptz NOT NULL,
  depot_id int NOT NULL,
  status smallint NOT NULL,
  scanner_id int NOT NULL,
  location text NOT NULL
);
CREATE INDEX scan_events_parcel_idx ON scan_events (parcel_id, scanned_at);

-- 125,000 parcels with 8 scans each, arriving in mixed order over one day.
INSERT INTO scan_events (parcel_id, scanned_at, depot_id, status, scanner_id, location)
SELECT 900000000 + (g::bigint * 7919) % 125000,
       timestamptz '2026-11-17' + g * interval '86 milliseconds',
       1 + g % 60, (g % 8)::smallint, 1 + g % 5000,
       'D' || lpad((g % 60)::text, 2, '0') || '-BELT-' || (g % 12)
FROM generate_series(1, 1000000) AS g;

SELECT 'table' AS part, pg_relation_size('scan_events') AS bytes,
       round(pg_relation_size('scan_events') / 1e6, 1) AS bytes_per_row
UNION ALL
SELECT 'primary key', pg_relation_size('scan_events_pkey'),
       round(pg_relation_size('scan_events_pkey') / 1e6, 1)
UNION ALL
SELECT 'parcel index', pg_relation_size('scan_events_parcel_idx'),
       round(pg_relation_size('scan_events_parcel_idx') / 1e6, 1)
UNION ALL
SELECT 'total', pg_total_relation_size('scan_events'),
       round(pg_total_relation_size('scan_events') / 1e6, 1);
Terminal · throwaway PostgreSQL 18 in Docker, data in memory
docker run -d --name sizecheck -e POSTGRES_PASSWORD=lab \
  --tmpfs /var/lib/postgresql -v "$PWD":/work:ro postgres:18-alpine >/dev/null
until docker exec sizecheck pg_isready -h 127.0.0.1 -U postgres -q; do sleep 1; done
docker exec sizecheck psql -U postgres -X -q -f /work/size_check.sql
docker rm -f -v sizecheck >/dev/null
Expected output (PostgreSQL 18 on a 64-bit machine)
     part     |   bytes   | bytes_per_row 
--------------+-----------+---------------
 table        |  76562432 |          76.6
 primary key  |  22487040 |          22.5
 parcel index |  38846464 |          38.8
 total        | 137945088 |         137.9
(4 rows)

The measured cost is about 138 bytes per row, 38% more than the guess. The table alone takes 77 bytes per row: each row carries a fixed header of 23 bytes, padding aligns the data to 8-byte boundaries on 64-bit machines, and each row has a 4-byte pointer in its page, as PostgreSQL's page layout documentation describes. The primary key adds 22 bytes. The (parcel_id, scanned_at) index adds 39, more than its 16 bytes of key: each entry also has an 8-byte header and a 4-byte pointer, and because rows arrive in mixed parcel order, its pages split and stay partly empty. These numbers are PostgreSQL's: MySQL's InnoDB, for example, stores rows inside the primary-key index, so its overheads differ. Measure on the engine you will run.

Terminal · rerun with the measured size
python3.12 scan_capacity.py 138
Expected output
138 bytes per row, 400 days online, 0.0 TB of other data   (share of each limit used)
scenario  year  rows/day  online TB     disk  restore   writes    cache
best         1      7.2M       0.40      17%      25%       3%      11%
best         2      8.6M       0.48      20%      30%       4%      13%
best         3     10.4M       0.57      24%      36%       5%      16%
expected     1     16.0M       0.88      37%      55%       9%      24%
expected     2     21.6M       1.19      50%      75%      12%      33%
expected     3     29.2M       1.61      67%     101%      17%      44%  <- over
worst        1     30.0M       1.66      69%     103%      23%      45%  <- over
worst        2     45.0M       2.48     104%     155%      35%      68%  <- over
worst        3     67.5M       3.73     155%     233%      52%     102%  <- over

The measurement moved the decision. The expected case now crosses the restore limit in year 3, and the worst case already in year 1. Had we trusted the guess, the plan would have said "no change needed for three years".

05. Step 4: test the node assumption, then decide what to change

First, test the assumption behind every table so far: that scan events have the node to themselves. Lesson 1 keeps 2.2 TB of parcels online. Suppose they shared this primary:

Terminal · 2.2 TB of parcels on the same node
python3.12 scan_capacity.py 138 400 2.2
Expected output
138 bytes per row, 400 days online, 2.2 TB of other data   (share of each limit used)
scenario  year  rows/day  online TB     disk  restore   writes    cache
best         1      7.2M       0.40     108%     162%       3%      11%  <- over
best         2      8.6M       0.48     112%     167%       4%      13%  <- over
best         3     10.4M       0.57     116%     173%       5%      16%  <- over
expected     1     16.0M       0.88     128%     193%       9%      24%  <- over
expected     2     21.6M       1.19     141%     212%      12%      33%  <- over
expected     3     29.2M       1.61     159%     238%      17%      44%  <- over
worst        1     30.0M       1.66     161%     241%      23%      45%  <- over
worst        2     45.0M       2.48     195%     293%      35%      68%  <- over
worst        3     67.5M       3.73     247%     370%      52%     102%  <- over

Every scenario is over the restore limit from year 1, and the parcels' writes and hot pages would also compete for the node. Every dataset on a node counts against its limits. That is why the record in lesson 2 gives scan events a primary of their own.

With their own node, there are two kinds of fix. The first shrinks what the node holds. Old scans are read rarely, mostly for disputes, so the 400 online days could become 90, with older scans exported to the archive and queried there. With daily or monthly table partitions, old partitions are exported and then dropped, which frees their space at once. Deleting rows instead leaves the space inside the table for reuse after VACUUM; it is usually not returned to the operating system (only completely empty pages at the end of a table can be). Rerun the check with 90 days:

Terminal · 90 days online
python3.12 scan_capacity.py 138 90
Expected output
138 bytes per row, 90 days online, 0.0 TB of other data   (share of each limit used)
scenario  year  rows/day  online TB     disk  restore   writes    cache
best         1      7.2M       0.09       4%       6%       3%      11%
best         2      8.6M       0.11       4%       7%       4%      13%
best         3     10.4M       0.13       5%       8%       5%      16%
expected     1     16.0M       0.20       8%      12%       9%      24%
expected     2     21.6M       0.27      11%      17%      12%      33%
expected     3     29.2M       0.36      15%      23%      17%      44%
worst        1     30.0M       0.37      16%      23%      23%      45%
worst        2     45.0M       0.56      23%      35%      35%      68%
worst        3     67.5M       0.84      35%      52%      52%     102%  <- over

Every scenario now fits, except the worst case in year 3, where the hot week no longer fits in the cache (102%). Fixing one limit exposes the next, so rerun the check after every change.

The second kind of fix is sharding. Whichever you choose, start before the crossing: if a migration takes six months, and the expected case crosses at the start of year 3, the work must start in the middle of year 2. Note the date in the decision record, with the measurements that would move it, such as actual volume growth.

06. Step 5: if you shard, check the key for hot spots

A shard key spreads writes only as evenly as its values. The script below samples one day's scans with a realistic skew (a few hub depots handle most parcels), places them on four shards by three candidate keys, and reports the busiest shard's share and the hottest key value's peak rate in the expected case for year 3.

Python · shard_skew.py
"""Which partition key spreads one day of scan writes evenly? (Python 3.12)"""
import random
from collections import Counter
from zlib import crc32

rng = random.Random(7)
SHARDS = 4
DEPOTS = 60
# A few hub depots handle most parcels: depot k gets weight 1 / k**0.8.
depot_weight = [1 / k**0.8 for k in range(1, DEPOTS + 1)]
PEAK_ROWS_S = 1_013  # expected case, year 3, from scan_capacity.py

# A sample of 100,000 scans from one day: (parcel id, depot id, day).
scans = [(rng.randrange(10**9), rng.choices(range(1, DEPOTS + 1), depot_weight)[0],
          "2026-11-17") for _ in range(100_000)]

KEYS = {
    "hash(parcel_id)": lambda p, d, day: crc32(str(p).encode()) % SHARDS,
    "depot_id": lambda p, d, day: d % SHARDS,
    "day": lambda p, d, day: crc32(day.encode()) % SHARDS,
}
print(f"{'partition key':<17}{'busiest shard':>14}{'hottest value':>15}"
      f"{'its peak':>10}")
for name, shard_of in KEYS.items():
    shards = Counter(shard_of(*scan) for scan in scans)
    column = {"hash(parcel_id)": 0, "depot_id": 1, "day": 2}[name]
    values = Counter(scan[column] for scan in scans)
    top_share = values.most_common(1)[0][1] / len(scans)
    print(f"{name:<17}{max(shards.values()) / len(scans):>14.1%}{top_share:>15.2%}"
          f"{top_share * PEAK_ROWS_S:>8,.0f}/s")
Terminal
python3.12 shard_skew.py
Expected output
partition key     busiest shard  hottest value  its peak
hash(parcel_id)           25.2%          0.00%       0/s
depot_id                  32.4%         14.29%     145/s
day                      100.0%        100.00%   1,013/s

Hashing the parcel id spreads writes almost perfectly (25.2% against an ideal 25%), and R1, all scans of one parcel, still reads a single shard. Its hottest value rounds to zero: one parcel gets only a few scans a day. Sharding by depot leaves one shard with 32% of the writes. Sharding by day sends all of today's writes to one shard, whatever the shard count.

The same check applies to a managed key-value store. DynamoDB's documentation (checked on 17 November 2026) gives each partition at most 1,000 write units per second, one unit per write of up to 1 KB. A table keyed by day would need 1,013 per second on one key at the expected year-3 peak, over that limit. An index keyed by depot would see 145 per second on its busiest value, but every index write also consumes capacity, and an index short of it can throttle writes to the table.

07. Check your understanding

Practice check · 3 questions

Scale checks

Three situations from other systems. Use the method, not the parcel numbers.

Q1. A spreadsheet says 120 bytes per row, so 400 million rows need 48 GB. You load a 1% sample (4 million rows) into PostgreSQL with the real schema and indexes, and it reports 700 MB for the table plus its indexes. Each node, primary or replica, holds a full copy. What should the estimate per node be?
Q2. A PostgreSQL events table keeps 90 days of data: a nightly job deletes rows older than 90 days, and autovacuum runs normally. Volume is steady. After the first deletes, the table's size on disk stops growing but never shrinks. What explains this?
Q3. A DynamoDB table receives 1,500 new items per second, each 0.8 KB. It has two global secondary indexes that project all attributes, and every item carries both index keys. How many write units per second does this workload consume?
Practice only: not graded, not saved, not evidence.

08. Apply it

Pick the two highest-traffic datasets of your marketplace (from your lesson 1 cards) and check the stores you chose in lesson 2:

  1. Write the inputs table with best, expected and worst values and a basis for each, and the limits of one node with a basis for each.
  2. Copy scan_capacity.py, replace the inputs and limits, and find the binding limit and the year it is crossed in each scenario.
  3. Name the guess that moves the result most and how you would measure it; if you can, load a sample and rerun.
  4. If sharding may be needed, test two candidate keys with a copy of shard_skew.py, and check that your main read stays on one shard.

09. Review prompt

Without looking back, answer in your own words:

  1. Why did the restore limit bind before the disk limit, and where did that limit come from?
  2. What made the measured bytes per row larger than the column values, and why does it differ between engines?
  3. What is the difference between table partitioning and sharding, and which one did retention need?
  4. How do you test a partition key for hot spots, and what else must a good key do?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check