2020-12-14 00:51:25+00:00

For SaaS and hardware platforms, charging customers based on active usage requires tracking device uptime. If client devices send status updates (heartbeats) periodically, you can compute billing metrics based on these intervals. However, writing a database record for every heartbeat will overwhelm datastore limits. An efficient uptime billing engine aggregates periodic heartbeats into session records, minimizing database writes.

An efficient uptime billing engine aggregates periodic heartbeats into session records, minimizing database writes.


1. Accumulating Heartbeats

Whenever a client heartbeat arrives, the server retrieves the current active session. If the time difference is within the heartbeat interval, the server updates the session's duration instead of creating a new record:

# Aggregating heartbeats on Cloud Datastore
from datetime import datetime, timezone

def record_device_heartbeat(device_id):
    now = datetime.now(timezone.utc)
    session = get_active_session(device_id)
    
    if session and (now - session.last_heartbeat).seconds < 300: # 5-min window
        session.duration += (now - session.last_heartbeat).seconds
        session.last_heartbeat = now
        session.put()
    else:
        # Start a new billing session
        new_session = BillingSession(device_id=device_id, start_time=now, last_heartbeat=now, duration=0)
        new_session.put()

2. Accurate Invoice Computations

By aggregating usage into sessions, write operations are minimized, and invoicing systems can query the session table directly to compute accurate billing metrics.

Idempotent Cloud Tasks & Push Queue Deduplication on Google Cloud

Assign deterministic task names and database idempotency keys so retried Cloud Tasks never duplicate customer notifications or ledger entries.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs