Atomicity is per row, and that is the whole transactional story. All mutations in a single MutateRow call are applied atomically: they all happen or none do. Across two rows there is no atomicity, no isolation and no transaction of any kind - so if two pieces of data must change together, they must be in the same row. That single constraint shapes more Bigtable schemas than anything except the row key.
The practical consequence: design so invariants live within one row. A device's current state and its alert flag in one row is atomic; the device's state in one row and an aggregate in another is not, and the aggregate will be wrong sometimes.
Conditional mutations - CheckAndMutateRow - evaluate a filter against a row and apply one set of mutations if it matched and another if it did not. This gives you compare-and-set on a single row, which is enough for optimistic locking, state machine transitions and create-if-absent. The important detail: the predicate is a filter, not an expression, so you express "the value is X" as a filter chain that matches, which is more awkward and more flexible than it first appears.
Read-modify-write - ReadModifyWriteRow - does server-side increments and appends atomically. increment treats the cell as a 64-bit big-endian integer; append concatenates bytes. These are genuinely atomic and genuinely useful for counters, and they have two caveats: they are not idempotent, so a retried increment double-counts and the client library's automatic retries make that a real risk; and they conflict with the versioning model, so the family should keep one version.
Batches send many mutations in one request, and the failure mode is the one to design for: a batch can partially succeed. The response carries a status per entry, and entries that failed must be retried individually - code that checks only for an exception loses writes silently. The same applies to batch reads.
App profiles are Bigtable's routing and isolation mechanism, and they are more useful than they look. A profile specifies which cluster a request goes to (single-cluster or multi-cluster routing), whether single-row transactions are allowed, and a priority. The design pattern: a profile per workload, so that a batch analytics job and a serving application use different profiles, and - with single-cluster routing - can be pointed at different clusters. That is how you isolate a heavy batch job from your serving traffic without a second instance.
The constraint worth knowing: conditional and read-modify-write operations require single-cluster routing, because they cannot be made safe across clusters that accept writes independently. So a profile with multi-cluster routing silently cannot do your compare-and-set, and you discover that at the API rather than in the documentation.
Laboratory exercise 3 - atomicity and routing.
Build a telemetry ingestion service and run at least 200 concurrent clients.
Demonstrate the single-row boundary: implement a device state update plus an aggregate counter in two rows, run it concurrently with failures injected, and show the aggregate diverging. Then redesign so the invariant is in one row and show it holding.
Implement a state machine transition with CheckAndMutateRow and run it concurrently for the same device, showing exactly one transition succeeding.
Implement a counter with ReadModifyWriteRow, then demonstrate the retry double-count: inject a timeout that causes the client to retry and show the counter over-counting. Then make it idempotent with a conditional mutation keyed on a request id and show it correct.
Demonstrate partial batch failure: send a batch containing one invalid mutation and show the others succeeding, with the per-entry status. Then write the retry logic correctly.
Create two app profiles - a serving profile with single-cluster routing and an analytics profile - and show them routing differently. Then attempt a CheckAndMutateRow through a multi-cluster profile and capture the error.
Deliverable: the service, the two-row divergence demonstrated and fixed, the concurrent state machine test, the counter double-count with its idempotent fix, the partial batch failure with correct retry logic, the app profile routing evidence, and the multi-cluster conditional error.
# ==================================================================
# *** ATOMICITY IS PER ROW. That is the whole transactional story. ***
# ==================================================================
# All mutations in ONE MutateRow are atomic. Across two rows there is
# NO atomicity, NO isolation and NO transaction of any kind.
#
# *** SO IF TWO PIECES OF DATA MUST CHANGE TOGETHER, THEY MUST BE IN
# *** THE SAME ROW. *** That constraint shapes more Bigtable schemas
# than anything except the row key.
row = table.direct_row(b"dev#d-0042#state")
row.set_cell("cur", b"status", b"alerting")
row.set_cell("cur", b"temp_c", b"84.2")
row.set_cell("cur", b"alert_since", b"2026-11-30T14:04:00Z")
row.set_cell("cur", b"alert_count", struct.pack(">q", 7))
row.commit()
# All four, or none. The device's state and its alert flag are
# consistent with each other, always.
# WHAT YOU CANNOT DO - and the lab demonstrates the divergence:
# row A: dev#d-0042#state -> status = alerting
# row B: site#s-01#counts -> alerting_devices += 1
# A failure between them leaves the counter wrong, permanently,
# with nothing to detect it. There is no transaction available.
#
# THE FIX IS THE SCHEMA: put the invariant in one row, or accept that
# the aggregate is approximate and recompute it from the source of
# truth on a schedule. Those are the options; pick one and say so.
# ==================================================================
# CONDITIONAL MUTATIONS: compare-and-set on ONE row.
# ==================================================================
from google.cloud.bigtable import row_filters as rf
cond = table.conditional_row(
b"dev#d-0042#state",
# *** THE PREDICATE IS A FILTER, NOT AN EXPRESSION. *** You
# express "the value is normal" as a filter chain that MATCHES:
filter_=rf.RowFilterChain(filters=[
rf.FamilyNameRegexFilter("cur"),
rf.ColumnQualifierRegexFilter(b"status"),
rf.CellsColumnLimitFilter(1),
rf.ValueRegexFilter(b"normal"),
]))
cond.set_cell("cur", b"status", b"alerting", state=True) # IF matched
cond.set_cell("cur", b"status", b"normal", state=False) # IF NOT
matched = cond.commit()
# matched tells you which branch ran. Run it concurrently for the
# same device: EXACTLY ONE transition succeeds.
# Create-if-absent:
cond = table.conditional_row(
b"dev#d-0042#meta",
filter_=rf.PassAllFilter(True)) # matches if the row EXISTS
cond.set_cell("meta", b"created_at", b"...", state=False) # only if NOT
cond.commit()
# OPTIMISTIC LOCKING with a version cell:
cond = table.conditional_row(
b"dev#d-0042#state",
filter_=rf.RowFilterChain(filters=[
rf.ColumnQualifierRegexFilter(b"version"),
rf.CellsColumnLimitFilter(1),
rf.ValueRegexFilter(struct.pack(">q", 7)),
]))
cond.set_cell("cur", b"version", struct.pack(">q", 8), state=True)
cond.set_cell("cur", b"status", b"updated", state=True)
if not cond.commit():
pass # someone else wrote first: re-read and retry
# ==================================================================
# READ-MODIFY-WRITE: atomic increments. AND NOT IDEMPOTENT.
# ==================================================================
rmw = table.append_row(b"site#s-01#counts")
rmw.increment_cell_value("cur", b"readings", 1)
# treats the cell as a 64-bit BIG-ENDIAN integer
rmw.append_cell_value("hist", b"event_log", b"|reading")
# concatenates bytes
result = rmw.commit()
new_value = struct.unpack(">q", result["cur"][b"readings"][0][0])[0]
# *** THE TRAP: increment IS NOT IDEMPOTENT, AND THE CLIENT LIBRARY
# *** RETRIES AUTOMATICALLY ON TIMEOUTS AND TRANSIENT ERRORS. ***
# A timed-out increment may have applied, and the retry applies it
# again. Demonstrate the over-count in the lab.
#
# THE IDEMPOTENT FIX: a conditional mutation keyed on a REQUEST ID,
# in the same row as the counter so it is atomic with it:
cond = table.conditional_row(
b"site#s-01#counts",
filter_=rf.RowFilterChain(filters=[
rf.ColumnQualifierRegexFilter(b"req_" + request_id.encode()),
rf.CellsColumnLimitFilter(1),
])) # matches if ALREADY SEEN
cond.set_cell("meta", b"req_" + request_id.encode(), b"1", state=False)
cond.set_cell("cur", b"readings_delta", struct.pack(">q", 1), state=False)
cond.commit()
# A repeat matches the filter and the state=False branch does not
# run. Note this costs you the server-side increment, so the total
# becomes a sum of deltas - which is the trade.
#
# ALSO: increments conflict with the versioning model. Keep the
# family at ONE VERSION, or every increment leaves a version behind.
# ==================================================================
# BATCHES: *** A BATCH CAN PARTIALLY SUCCEED. ***
# ==================================================================
rows = []
for device_id, ts, temp in readings:
r = table.direct_row(key_promoted(device_id, ts))
r.set_cell("hist", b"temp_c", struct.pack(">d", temp), timestamp=ts)
rows.append(r)
statuses = table.mutate_rows(rows)
failed = []
for i, status in enumerate(statuses):
if status.code != 0:
failed.append((i, status.code, status.message))
# *** CODE THAT ONLY CHECKS FOR AN EXCEPTION LOSES WRITES SILENTLY.
# *** A batch returns a STATUS PER ENTRY, and failures must be
# *** RETRIED INDIVIDUALLY with backoff. ***
#
# Retry only the failures - re-sending the whole batch re-applies
# the successes, which matters if any of them were increments:
if failed:
retry = [rows[i] for i, _, _ in failed]
table.mutate_rows(retry)
# The same for batch reads: a RowSet of many point lookups is one
# request and far cheaper than N requests, and you must handle
# rows that come back absent.
rs = RowSet()
for d in device_ids:
rs.add_row_key(f"dev#{d}#state".encode())
found = {r.row_key: r for r in table.read_rows(row_set=rs)}
missing = [d for d in device_ids
if f"dev#{d}#state".encode() not in found]
# ==================================================================
# APP PROFILES: routing and ISOLATION. More useful than they look.
# ==================================================================
# gcloud bigtable app-profiles create serving \
# --instance=telemetry --route-to=prod-c1 \
# --transactional-writes \
# --description="Serving traffic, single cluster"
#
# gcloud bigtable app-profiles create analytics \
# --instance=telemetry --route-to=prod-c2 \
# --description="Batch jobs, isolated from serving"
#
# gcloud bigtable app-profiles create failover \
# --instance=telemetry --route-any \
# --description="Multi-cluster: availability over consistency"
serving = instance.table("telemetry", app_profile_id="serving")
analytics = instance.table("telemetry", app_profile_id="analytics")
# *** THE DESIGN PATTERN: A PROFILE PER WORKLOAD. *** With
# single-cluster routing they point at DIFFERENT CLUSTERS, so a heavy
# batch job cannot affect serving latency - WITHOUT a second
# instance. That is the isolation mechanism, and it is the main
# reason to run two clusters even in one region.
# *** THE CONSTRAINT YOU DISCOVER AT THE API: ***
# CONDITIONAL and READ-MODIFY-WRITE OPERATIONS REQUIRE
# SINGLE-CLUSTER ROUTING. They cannot be made safe across clusters
# that accept writes independently.
failover_tbl = instance.table("telemetry", app_profile_id="failover")
# cond = failover_tbl.conditional_row(...)
# cond.commit()
# -> FailedPrecondition: Table ... : CheckAndMutateRow is not
# supported by this app profile (multi-cluster routing)
#
# So a profile chosen for AVAILABILITY silently cannot do your
# compare-and-set. Which profile an operation uses is therefore a
# correctness decision, not a routing preference.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.