Internet of Things (IoT) Integration

Self-Hosted MQTT vs Managed IoT on a Solo Budget

A solo freelancer can make an IoT integration work without buying a platform, but the delivery method can quietly become an unpaid support contract. My default is a scheduled pull from the device vendor’s API onto a client-owned machine, not a public webhook. I would change that default only when a delayed reading has a defined cost and the client will own the managed account that receives events.

A scheduled pull wins when the client can tolerate a short delay

The first option is a scheduled HTTPS pull: Python requests recent readings from the vendor’s JSON API, and SQLite stores them on a machine the client already operates. It wins when the API supports historical queries and the client can act on readings after a delay, because a failed run can request the same time window again. Its costs are an always-on client machine, a vendor API credential, backup storage, and someone willing to investigate missed runs.

The competing option is a managed webhook receiver: the vendor pushes each event to Cloudflare Workers, and the Worker writes it to D1. It wins when the vendor offers reliable webhooks and the client needs events soon after they occur, because a poll interval would otherwise impose avoidable delay. Its costs are a public endpoint, webhook authentication, managed-service limits, account administration, and a plan for events the vendor stops retrying. Neither option removes operational work; each puts that work in a different place.

For the pull, I would use Python 3.11’s urllib.request and sqlite3 before adding a queue or an SDK, because a small dependency set makes a single-purpose job easier for a client to reinstall. The following job runs with the Python standard library once IOT_API_URL points to an HTTPS endpoint returning a readings array and IOT_API_TOKEN contains its bearer token. Each reading needs device, observed_at, and value fields.

import json, os, sqlite3, urllib.request
req = urllib.request.Request(os.environ["IOT_API_URL"],
    headers={"Authorization": "Bearer " + os.environ["IOT_API_TOKEN"]})
with urllib.request.urlopen(req, timeout=10) as response:
    readings = json.load(response)["readings"]
with sqlite3.connect("telemetry.sqlite3") as db:
    db.execute("CREATE TABLE IF NOT EXISTS samples (device TEXT, observed_at TEXT, value REAL, PRIMARY KEY(device, observed_at))")
    for item in readings:
        db.execute("INSERT OR IGNORE INTO samples VALUES (?, ?, ?)",
                   (item["device"], item["observed_at"], item["value"]))
print(f"processed {len(readings)} readings")

The 10-second timeout is a value to tune against the vendor’s normal response time; it prevents one hung request from occupying the job indefinitely. SQLite’s composite primary key makes overlapping pulls safe to repeat, provided the vendor preserves a stable timestamp for each device reading. Ask for RFC 3339 timestamps with offsets or UTC Z notation, because ambiguous local timestamps can create apparent duplicates when clocks change. The printed count reports records processed, not newly stored records, so it must not be presented as proof of complete delivery.

A cron schedule of */5 * * * * is an initial setting to adjust, not a latency guarantee: a reading may already be old when the vendor publishes it. More importantly, the URL must request a repeatable historical window or cursor, because an API that returns only the latest value cannot repair a gap after the machine is offline. I would not build the pull around “latest reading” just to shorten the first invoice; it makes a missed run permanently invisible.

A managed webhook wins only when faster delivery changes an action

“Real time” is too vague to justify a public receiver. Write down the action first: who notices an abnormal value, what they do, and how late the value may arrive before that action loses its value. If the client reviews a report each morning, a five-minute poll may be adequate because faster transport does not move the review forward. If an operator must respond while a condition is still present, a webhook may earn its extra moving parts because waiting for the next poll consumes the response window.

Cloudflare Workers and D1 provide a plausible managed path for a freelancer because the client can own the account instead of acquiring a server for the freelancer to maintain. Ownership is a contract condition, not a billing detail: the client needs access to deploy the Worker, rotate secrets, inspect failures, and continue service after the engagement ends. Check the current Workers and D1 pricing pages before quoting, since request allowances and database charges are separate limits rather than a blanket promise that the integration is free.

As a scale check, 60 devices sending one event per minute produce a calculated 86,400 events per day if each event makes one request. Cloudflare publishes a 100,000-requests-per-day allowance for Workers on its Free plan; that allowance leaves little headroom in this example for retries, tests, or other Workers in the account. Those figures do not establish a bill, because the actual plan, D1 usage, and request shape still need checking. They do establish a useful question for the client: will events arrive individually, or can the vendor batch them?

A webhook must authenticate the sender before writing to D1, because a public URL that accepts arbitrary JSON lets outsiders fill the database or forge readings. Use the vendor’s signature scheme if it has one, verify its HMAC-SHA256 over the raw request body, and reject timestamps outside a configured replay window. Keep the signing secret in a Worker secret rather than source code. Give each event a vendor event ID, or a documented composite key, because retries without idempotency can turn one device event into several database rows.

Before accepting a push-only design, ask the vendor what happens after an HTTP 429, a timeout, and an extended outage; the answer determines whether the receiver can recover rather than merely resume. Honor Retry-After where the vendor uses it, but do not assume a retry policy exists without documentation. A webhook becomes the stronger choice when the vendor offers event replay or a historical API alongside delivery, because the freelancer can then repair gaps without inventing lost readings.

Recovery ownership matters more than the first successful reading

Read Ship Your First IoT Integration Without a Platform Team beside the client contract: a successful upload is a useful milestone, but it does not identify who restores a credential or replays missing data. For a solo freelancer, that omission matters because an informal “call me if it breaks” arrangement can outlast the fixed-price build. Put the recovery owner, access method, and paid support boundary in writing before selecting either transport.

For the scheduled pull, the handoff should include the cron entry, environment-variable names, API permissions, the SQL schema, and a command for running the job manually. Back up telemetry.sqlite3 to storage the client controls, using a tool such as restic if the client has a supported backup destination; a database on the same machine as the job is not a recovery copy. If another process reads SQLite while the job writes, test SQLite WAL mode and the client’s backup procedure together, because copying live database files without understanding their companion files can produce an incomplete restore.

For the Worker, the handoff should include access to the Cloudflare account, the deployed code, the D1 database binding, secret-rotation instructions, and the vendor’s webhook configuration. Test a bad signature and a temporary database failure, because a receiver that always answers success can cause the vendor to discard an event it never stored. Decide whether the Worker returns a non-success HTTP status on failed writes only after checking the vendor’s retry rules; otherwise the correct-looking response may create either silent loss or a retry storm.

Agree on one alert recipient who can act. An email sent only to the freelancer does not make the client independent, and an alert sent to nobody is merely a log entry. For either approach, retain enough identifiers to trace a reading from vendor response or webhook event through to its stored row. Avoid putting API tokens or full payloads in routine logs, because those logs may be easier to share than the credential store and may contain data the client did not agree to retain.

A paid recovery test should choose the architecture

Read Scope IoT Integration Around Metrics That Prove It Works with some skepticism: a green delivery chart is insufficient if nobody can recover a missing afternoon. The acceptance test should connect a measurement to an action. Track event lag from the device’s observed timestamp to durable storage, coverage against the readings the vendor says exist, and recovery time after an intentionally interrupted connection. If the source supplies no reliable event count, say so; a percentage with an unknowable denominator is not evidence of completeness.

Choose thresholds with the client rather than borrowing them from a dashboard. A proposed 15-minute lag threshold is a starting value to negotiate against the operator’s response window; it is not a property of HTTPS, Workers, or SQLite. A pilot should record the observed lag distribution, including its p95, because an average can hide a small number of readings that arrive too late to use. Record the time of the last successfully stored event as well, since a silent system can have an excellent historical p95.

Make the trial deliberately inconvenient. Stop the scheduled job, let its normal interval pass, restart it, and compare the recovered rows with the vendor’s historical endpoint. For the webhook, reject a signed request temporarily and inspect the vendor’s retry record before restoring the receiver. Rotate the relevant credential in the client-owned account while the client watches. These exercises are worth paying for because they expose contractual and vendor limitations before the integration is treated as dependable.

If both approaches pass, I would choose the scheduled pull for a client without an operator watching live events, because its historical query makes failures easier to inspect and replay on equipment the client already owns. I would choose the managed webhook when the measured delay of polling exceeds an agreed action window and vendor replay is documented, because lower arrival time then buys a specific operational benefit. If neither can recover an outage, I would narrow the promise in the contract rather than describe the system as reliable.

The first decision is whether lost readings can be replayed

Before writing a receiver, request the vendor’s API and webhook documentation and find the exact historical-query or event-replay limit. Then ask the client to name one action that depends on a reading and the latest time that reading remains useful. Those answers give you a defensible default: poll if replay and delay permit it; propose a webhook only if faster arrival changes that action and the client will own recovery.