Capstone - IoT Telemetry Service

Article · 8:00

Salted and promoted row keys, retention policies, and a hotspot analysis backed by Key Visualizer.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

The system. An IoT telemetry service: 100,000 devices reporting readings every few seconds, readings queried per device and per site, current state held separately from history, retention enforced by garbage collection, and a batch analytics path for the queries no row key can serve.

Three invariants must hold:

  1. Every reading written is readable through its intended query path - demonstrated for each numbered query.
  2. No key range takes disproportionate traffic: hottest-node CPU stays within a stated factor of average CPU at the declared load, demonstrated with Key Visualizer and not only with metrics.
  3. Retention holds: no reading older than the stated retention period is returned, including the garbage collection delay - which means the application filters on the timestamp as well as relying on the policy.

Invariant 3 is the one that catches people, because garbage collection is applied at compaction and a cell past its policy can still come back. A design that relies on the GC policy alone for a retention guarantee does not have one.

What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone.

A row key design with the reasoning shown, and Key Visualizer evidence. The numbered query list, the key scheme, which queries are range scans and which are not, and - for the ones that are not - which of the three answers you chose (write it again, accept a batch scan, or use another system). A capstone without a Key Visualizer image has not demonstrated invariant 2, because this is the one engine in the programme where the diagnostic is a picture and the picture is conclusive.

A measured node count and a cost model derived from it. Bigtable does not bill per request, so the cost model is a node count - and a node count is only defensible if you measured throughput per node with realistic row sizes and your actual key distribution. Include the scaling test: throughput at two node counts, showing it scales.

A defensible account of failure modes, operational limits and cost. Three things specifically: the hotspot diagnosis path, with the average-against-hottest-node distinction stated; the routing consistency decision per operation, with the multi-cluster miss rate measured; and the single-row atomicity boundary, with the invariants that live inside one row named.

Deliverables: architecture diagram including clusters and app profiles; the numbered query list with each query's key pattern; the row key scheme with the distribution reasoning; Key Visualizer images; source code including batch retry handling and the idempotent counter; reproducible load generator with realistic row sizes; benchmark report with average and hottest-node CPU and the scaling test; security review including the tenancy decision; recovery runbook with measured RPO and RTO; cost model from the measured node count; and a short design defence.

PY Example 1 177 lines
# ================= The query list, and the honest answers =========
#  #  query                          key pattern            answer
#  1  latest reading, one device     point, reversed ts     range scan
#  2  one device, one day            prefix dev#D#rev       range scan
#  3  one device, a time range       range on dev#D#rev     range scan
#  4  all devices at a site, one day prefix site#S#day      SECOND WRITE
#  5  one device's current state     point dev#D#state      point
#  6  one device's metadata          point dev#D#meta       point
#  7  devices needing firmware       *** no key serves it ***
#                                    -> SECOND WRITE: fw#VERSION#dev#D
#  8  readings above a threshold     *** no key serves it ***
#                                    -> BATCH: export to BigQuery
#
# Queries 7 and 8 are where the design shows judgement. With one
# index there are only three answers - write it again, accept a batch
# scan, or use another system - and the capstone states which, per
# query, with the cost of each.

# ================= The key scheme =================================
MAX_TS = 9999999999

def k_reading(device_id, ts):
    """Readings: device promoted, timestamp reversed."""
    rev = MAX_TS - int(ts.timestamp())
    return f"dev#{device_id}#{rev:010d}".encode()
#   DEVICE PROMOTED -> 100,000 distinct prefixes -> writes spread
#   across the whole key space. NO SALT NEEDED, because the device id
#   is high-cardinality and the queries are per-device. That is
#   field promotion doing its job, and saying so is the defence.

def k_state(device_id):
    return f"dev#{device_id}#state".encode()

def k_site(site_id, day, device_id, ts):
    """Query 4's second write. Site is LOW cardinality, so SALT."""
    rev = MAX_TS - int(ts.timestamp())
    tail = f"site#{site_id}#{day}#{device_id}#{rev:010d}"
    return f"{stable_hash(tail) % 16:02d}#{tail}".encode()
#   200 sites over 100,000 devices: site#S# alone WOULD hotspot, so
#   this one IS salted - 16 buckets, read as 16 ranges and merged.
#   TWO KEY SCHEMES IN ONE DESIGN, each chosen for its own query's
#   cardinality. That contrast is the modelling lesson.

# ================= Invariants, as runnable checks =================

# 1. Every reading readable by its intended path - one assertion per
#    numbered query, run after every deployment.

# 2. *** NO KEY RANGE TAKES DISPROPORTIONATE TRAFFIC. ***
#      cpu_load_hottest_node / cpu_load  < 1.5   at declared load
#
#      0.61 / 0.58 = 1.05    PASSES
#      0.98 / 0.21 = 4.67    FAILS - and the AVERAGE LOOKS FINE
#
#    *** AND IT MUST BE SHOWN IN KEY VISUALIZER, not only in
#    *** metrics. *** This is the one engine in the programme where
#    the diagnostic is a PICTURE and the picture is CONCLUSIVE: a
#    dark field with even activity passes; a bright line or diagonal
#    does not. A capstone without the image has not demonstrated
#    this invariant.

# 3. *** RETENTION HOLDS, INCLUDING THE GC DELAY. ***
#    GC is applied at COMPACTION, so a cell past its policy CAN
#    STILL BE RETURNED. A design relying on the GC policy ALONE does
#    not have a retention guarantee. So the application filters too:
import datetime
from google.cloud.bigtable import row_filters as rf

RETENTION_DAYS = 90
cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=RETENTION_DAYS)

flt = rf.RowFilterChain(filters=[
    rf.FamilyNameRegexFilter("hist"),
    rf.TimestampRangeFilter(rf.TimestampRange(start=cutoff)),
    rf.CellsColumnLimitFilter(1),
])
rows = table.read_rows(row_set=_prefix(f"dev#{device_id}#"), filter_=flt)
#   BELT AND BRACES: the GC policy reclaims the space; the FILTER
#   provides the GUARANTEE. Both, and the design says why.

# ================= Single-row atomicity, named =====================
# The invariants that live INSIDE ONE ROW, because nothing spans rows:
row = table.direct_row(k_state(device_id))
row.set_cell("cur", b"temp_c",      struct.pack(">d", temp))
row.set_cell("cur", b"status",      status.encode())
row.set_cell("cur", b"last_seen",   ts.isoformat().encode())
row.set_cell("cur", b"alert_active", b"1" if alerting else b"0")
row.commit()
#   The reading, the derived status and the alert flag are ALWAYS
#   consistent with each other. A design that put the alert flag in
#   a site-level row would have them disagree, with no transaction
#   available to fix it. NAMING this boundary is part of the defence.
#
# Site-level aggregates are therefore APPROXIMATE and recomputed
# from the device rows on a schedule. Stated, not discovered.

# ================= Batch writes, correctly ========================
rows = [_mk_reading_row(d, t, v) for d, t, v in batch]
statuses = table.mutate_rows(rows)
failed = [i for i, s in enumerate(statuses) if s.code != 0]
if failed:
    table.mutate_rows([rows[i] for i in failed])      # retry ONLY these
#   A batch CAN PARTIALLY SUCCEED. Checking only for an exception
#   loses readings silently, and re-sending the whole batch would
#   re-apply the successes.

# ================= Declare the baseline BEFORE measuring ==========
#
#   Instance:  2 clusters, SSD, autoscaling 6-30 nodes, CPU target 60
#   Profiles:  serving   single-cluster (c1), transactional writes
#              reads     multi-cluster  (staleness accepted, measured)
#              analytics single-cluster (c2), isolated from serving
#   Devices:   100,000, a reading every 5 s = 20,000 writes/s
#   Row size:  MEASURED - ~180 bytes per reading cell, not assumed
#   Retention: 90 days, GC policy AND a timestamp filter
#
#   Claim:
#     write a reading           p99 <  10 ms
#     latest reading (point)    p99 <   8 ms
#     one device, one day       p99 <  25 ms
#     site day (16 salted)      p99 <  60 ms
#     cpu_load_hottest / avg    <  1.5
#     multi-cluster read miss   ___ %  MEASURED - the cost of
#                                      availability, as a number
#     cluster failover (profile switch) < 2 min, MEASURED
#     restore RTO               < 45 min, MEASURED
#     RPO                       = the backup interval (24 h), stated
#
#   *** AND THE SCALING TEST, because the cost model depends on it: ***
#     throughput at  6 nodes:  ___ writes/s
#     throughput at 12 nodes:  ___ writes/s
#     -> roughly linear, which is what proves the key distributes
#
#   COST MODEL, from the MEASURED node count:
#     nodes       12 x 2 clusters x 730 h    = $____
#     storage     40 TB SSD x 2              = $____
#     egress      cross-zone replication     = $____
#     backups     30 days retention          = $____
#     TOTAL monthly                          = $____
#   Bigtable does not bill per request, so THE COST MODEL IS A NODE
#   COUNT - and a node count is only defensible if you measured
#   throughput per node with REALISTIC ROW SIZES and YOUR key
#   distribution.

# ================= Failure modes ==================================
#   timestamp-leading key       EVERY write to one tablet, one node.
#                               Adding nodes DOES NOT HELP. Field
#                               promotion. Invariant 2, Key Visualizer.
#   low-cardinality prefix      the same, for site#. Hence the salt
#                               on query 4's table.
#   unbounded row               a tablet that CANNOT BE SPLIT.
#                               Nothing fixes it but the schema.
#   autoscaling at minimum      average CPU low because ONE node is
#   while a node burns          hot. Autoscaling CANNOT fix a hotspot.
#                               The paired-metric alert catches it.
#   sudden traffic shape change REBALANCING TAKES MINUTES. Benchmarks
#                               must warm up; incidents must wait.
#   multi-cluster read miss     no read-your-writes. Measured, and
#                               the profile choice is per operation.
#   same cell, two clusters     LAST WRITE WINS, the other DISCARDED
#                               with no record. Region affinity.
#   conditional write through   REFUSED by the API. The profile
#   a multi-cluster profile     choice is a CORRECTNESS decision.
#   retried increment           DOUBLE COUNTS. The client retries.
#                               Idempotent via a request-id cell.
#   partial batch failure       silently lost readings if you only
#                               catch exceptions.
#   GC delay                    expired cells still returned. The
#                               timestamp filter is the guarantee.
#   value filter over a range   reads the WHOLE RANGE. Not an index.
#   CMEK not set at creation    cannot be added later.
#   tables per instance         the limit that breaks a
#                               table-per-tenant design at scale.
#
# Verify after every restore with sample keys, range boundaries and
# a counted keys-only prefix scan. There is no COUNT(*), and "the
# table is READY" is not verification.

Open this example in the editor and change it. Nothing you type is saved.

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course Why the row key is the only lesson, the emulator and the spend, the one diagnostic to master, and what to skip. 4 min read

Discussion

No questions on this topic yet. Sign in to ask the first one.