# Build a reliable MQTT client

> What to handle in a client for your account's alerts and lightning feeds so it stays correct for months.

Developers · How-to guide · https://wxalerts.org/docs/developers/mqtt/best-practices/

This is for a client you mean to leave running. A first client is in
[Subscribe to live alerts over MQTT](/docs/developers/mqtt-quickstart/); the
topics and payloads are in the [alerts feed](/docs/developers/mqtt/alerts/) and
[lightning feed](/docs/developers/mqtt/lightning/) references.

## Give every client its own ID

Two clients sharing a client ID take each other's session over in a loop. Derive
it from something stable and per-installation rather than hardcoding a constant.

## Hold one connection

A regular, meteorologist or EOC account may have one live connection, and a
second client with a different ID is refused. Run one client and fan out inside
your own program or broker. A [commercial
account](/docs/developers/mqtt/alerts/#commercial-accounts) also holds one, so bridge it
to your own broker for more readers.

## Reconnect slowly, with backoff

The broker allows 2 connect attempts a minute per account (5 for a commercial
account). A client that reconnects in a tight loop locks itself out, and the
refusals do not stop until the minute moves on. Wait at least 30 seconds after a
failed attempt, double the wait on each further failure up to five minutes, and
add some random jitter. Reset the wait after a connection that stayed up.

The broker remembers each login answer for a minute, so a refused login repeated
inside that minute is refused again without being counted. A connection held
open without reading the socket does not notice it has died: use a keepalive of
30 seconds or so and treat a missed one as a disconnect.

## Treat a refusal as a refusal

A refused login means the credential is wrong, revoked or renewed, or the account
is at its limit. Retrying faster does not help. Check the credential on the
[Credentials](/account/#credentials) page and, if you renewed its password,
update the client.

## Subscribe to your own filters

Subscribe to `V2/{user_id}/NWS/#` for alerts and `V2/{user_id}/GLM/#` for
lightning, the two filters shown on the Credentials page. They are the only topics
your credential may read, and they are well under the 20 subscription limit. A
subscription to anything else is refused.

## Catch up after every connect

Nothing is retained and nothing is replayed, so a client that starts or
reconnects knows nothing of what it missed. Subscribe first, then read the
current alerts from the [REST API](/docs/api/alerts/), and merge by `id`. See
[No retained messages, and how to catch up](/docs/developers/mqtt/retained-and-tombstones/).

## Decide an alert's state from `status` and `ends`

**`expires` is not the end of the hazard.** It is the "expect an update by"
deadline and routinely sits in the past on a live alert. Use `ends`, and trust
`status` over your own arithmetic.

**`action` is the latest VTEC action, not the state.** Go by `status`: `active`,
`cancelled` or `expired`.

## Key alerts on `id`

`id` is the same on every message about one alert. A message replaces what you
hold for that `id`. Use `places` to see which of your places it covers, and note
that a `cancelled` message from a released zone lists the places that it no
longer covers while the alert stays in effect elsewhere.

## Style alerts by `geometry_source`

`geometry_source` tells you how precise the shape is. `polygon` is a tight
storm-based warning polygon; `ugc` is a coarser union of forecast zones. Worth
styling differently. `geometry` is simplified for the wire and is `null` when
there is no shape, so draw nothing for those.

## Ignore what you do not know

New fields are added without changing `v`. Ignore any field you do not know,
and a value you do not recognise.

## Read the lightning feed

This client prints each strike from your lightning topic. It reads the username,
password and topic from the environment, like the
[quickstart](/docs/developers/mqtt-quickstart/).

```python
import json
import os
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, reason_code, properties):
    if not reason_code.is_failure:
        client.subscribe(os.environ["WXA_GLM_TOPIC"])   # V2/12345/GLM/#

def on_message(client, userdata, msg):
    batch = json.loads(msg.payload)
    for strike in batch["strikes"]:
        print(strike["lat"], strike["lon"], strike["t"], ", ".join(strike["places"]))

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, transport="websockets")
client.username_pw_set(os.environ["WXA_USER"], os.environ["WXA_PASS"])
client.tls_set()
client.on_connect = on_connect
client.on_message = on_message
client.reconnect_delay_set(min_delay=30, max_delay=300)
client.connect("mqtt.wxalerts.org", 443)
client.loop_forever()
```

## Age lightning out yourself

Strikes are not retained, so there is no message when a strike is over. Age
them out yourself, and ten minutes is a reasonable ceiling.

## Time lightning by observation, not arrival

A strike is typically 20 to 40 seconds old when it reaches you. That is older
than any sensible animation window. Fade on the observation time, `t`; animate on
arrival.

## Keep your own history

The REST API keeps 24 hours of flashes. For anything finer over a longer period,
keep the strikes yourself as they arrive.
