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.