posthog-python's atexit join blocks process exit for the whole retry backoff when a batch is mid-upload
posthog (Python) 7.13.0, default async mode (posthog.Posthog(api_key, host=...)). The client registers atexit.register(self.join) in its constructor. Wanted to know how long that can hold up process exit in a server worker whose supervisor hard-kills slow exits. The source comment says the consumer is a daemon thread 'so that it doesn't block program exit', and join() takes no timeout argument, so the bound is not obvious from the API. Calling client.shutdown() instead is worse for this purpose: it does queue.join() first, which is also unbounded.
Client.join() sets consumer.running = False and then calls consumer.join() with no timeout. The consumer only re-checks running between upload() calls, so:
- idle: it is inside
queue.get(timeout=flush_interval); join returns withinflush_interval(0.5s default). Measured 0.30s. - mid-upload: join waits for
request(batch)to finish, i.e. up tomax_retries + 1(default 4) attempts, each bounded bytimeout=15, withmin(2**attempt, 30)second sleeps in between. Against a refused endpoint (host="http://127.0.0.1:9") with one queued event,join()took 6.82s; against a host that hangs it can exceed a minute.
The daemon flag does not help because the atexit callback joins the thread explicitly.
Bounded replacement (0.50s in the same stuck state, one consumer thread abandoned):
def shutdown_posthog(client, timeout_s=2.0):
atexit.unregister(client.join) # bound methods compare equal; no-op if absent
deadline = time.monotonic() + timeout_s
while not client.queue.empty() and time.monotonic() < deadline:
time.sleep(0.05) # give queued events a chance
for c in client.consumers or []:
c.pause()
for c in client.consumers or []:
try:
c.join(max(0.0, deadline - time.monotonic()))
except RuntimeError: # never started
passCall it from the app's shutdown hook (off the event loop, e.g. asyncio.to_thread). Make sure nothing lazily constructs a new client afterwards, or a fresh unbounded atexit join gets registered.