GCP Engineer: Designing Idempotent Heartbeat Billing & Usage Trackers on Google Cloud Datastore
Metering time-based SaaS consumption—such as active GPU notebook sessions, WebRTC media rooms, or cloud IDE sandboxes—cannot rely solely on a final "session stop" event. If a worker node is preempted or a user closes their browser tab abruptly, relying on a stop event either leaks unbilled compute hours or overcharges customers for zombie sessions. As a Google Cloud Platform (GCP) Engineer and Backend Engineer, I architect monotonic, idempotent heartbeat metering engines on Google Cloud Datastore and Firestore Native Mode.
1. Monotonic Time-Bucket Deduplication vs. Naive Counter Increments
If a client emits a heartbeat every 30 seconds and retries on transient HTTP 502 errors, a naive handler that increments billed_seconds += 30 will double-bill the tenant on every retry. Instead, we quantize wall-clock timestamps into deterministic 30-second epoch slots (slot_id = int(timestamp // 30)) and store a bounded sliding bitmap or monotonic high-water mark inside an optimistic Datastore transaction:
import time
from google.cloud import datastore
client = datastore.Client()
HEARTBEAT_INTERVAL_SEC = 30
MAX_LEASE_GAP_SEC = 90 # Treat gaps > 90s as a disconnected pause
def record_usage_heartbeat(session_id: str, tenant_id: str, event_ts: int) -> dict:
slot_id = event_ts // HEARTBEAT_INTERVAL_SEC
key = client.key("TenantSessionMeter", f"{tenant_id}:{session_id}")
with client.transaction():
entity = client.get(key)
if entity is None:
entity = datastore.Entity(key=key, exclude_from_indexes=("recent_slots",))
entity.update({
"tenant_id": tenant_id,
"session_id": session_id,
"started_at": event_ts,
"last_slot_id": slot_id,
"billed_slots": 1,
"recent_slots": [slot_id],
"updated_at": int(time.time()),
})
client.put(entity)
return {"status": "initialized", "billed_seconds": HEARTBEAT_INTERVAL_SEC}
recent_slots = set(entity.get("recent_slots", []))
if slot_id in recent_slots:
# Idempotent retry for an already-metered 30s time window
return {
"status": "duplicate_noop",
"billed_seconds": entity["billed_slots"] * HEARTBEAT_INTERVAL_SEC,
}
last_slot = entity["last_slot_id"]
slot_delta = slot_id - last_slot
if 1 <= slot_delta <= (MAX_LEASE_GAP_SEC // HEARTBEAT_INTERVAL_SEC):
# Fill contiguous slots smoothly if 1-2 packets were delayed
newly_billed = slot_delta
else:
# Disconnected gap > 90s: only bill the newly resumed 30s slot
newly_billed = 1
recent_slots.add(slot_id)
pruned_slots = sorted(s for s in recent_slots if s >= slot_id - 32)
entity["last_slot_id"] = max(last_slot, slot_id)
entity["billed_slots"] += newly_billed
entity["recent_slots"] = pruned_slots
entity["updated_at"] = int(time.time())
client.put(entity)
return {
"status": "metered",
"billed_seconds": entity["billed_slots"] * HEARTBEAT_INTERVAL_SEC,
}
2. Preventing Hot-Key Contention & Closing Stale Sessions
Because each active session writes to its own scoped key (TenantSessionMeter(tenant_id:session_id)) at most once every 30 seconds, write frequency stays well below Cloud Datastore's 1 write/second/entity group limit—avoiding the lock contention we analyze in our Datastore Mode vs. Native Firestore Locks guide. A Cloud Scheduler cron runs every 5 minutes, querying sessions where updated_at < now - 120s and state == "ACTIVE", sealing the final usage ledger record and emitting an idempotent billing event into BigQuery and our PostgreSQL transactional outbox.
Need a certified GCP Engineer to architect usage-based SaaS metering on Cloud Datastore, Firestore, or BigQuery? Explore the 1-Day Engineering Sprint.