Repository navigation
fix: batch usage writes across messages - #14291
Conversation
The stats-usage worker wrote every message to ClickHouse as its own insert. Each insert is a new part that ClickHouse sorts into all ten event projections and merges again later, so modest traffic kept a small server busy. Messages now fold into one batch per worker process, written five seconds after it opens.
|
Review complete. 🟡 1 medium 📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to🟡 Medium — Failed flush discards the batch, defeating retry contract · StatsUsage.php:148–163 · // src/Appwrite/Platform/Workers/StatsUsage.php
148 $accumulator = $this->accumulator;
149 $this->accumulator = null;
150
151 if ($accumulator === null || $accumulator->count() === 0) {
152 return;
153 }
154
155 try {
156 if (!$accumulator->flush()) {
157 Console::error('Usage event flush returned false');
158 }
159 } catch (\Throwable $th) {The timer callback detaches This PR reworks the stats-usage worker to accumulate metrics in an
Reviewed commit: 14eecfa |
🟢 Tier S · Ready to merge
Stats usage messages are buffered in process-local accumulators and flushed by a one-shot timer, reducing ClickHouse inserts while preserving the worker's shutdown flush behavior. Accumulators are separated by event-time minute so events from different minutes retain their own timestamps and usage buckets. Latest changes: The latest commit replaces the single batch with per-minute accumulators and flushes all open minute batches together, preventing cross-minute folding.
📂 Walkthrough · 1
✅ Fixed since the last review · 1
Reviewed the commits since |
Security rulesNo new WARNING or ERROR findings from security rules. 32 existing findings tracked in
|
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
A folded event keeps the earliest time it absorbed, so a batch that crossed a minute boundary moved later events into the earlier minute, and at the turn of an hour or day into the earlier hour or day. Each minute of event time now gets its own accumulator, written in the same flush.
…/usage-batch-writes
What does this PR do?
Batches the stats-usage worker's ClickHouse writes, which is what keeps the bundled ClickHouse busy on a self-hosted install once traffic picks up.
The worker built a new
Accumulatorfor every queue message and flushed it before returning, so every API request and function execution became its ownINSERTintoprojects_usage_events. Each insert is a new part that ClickHouse sorts into all ten event projections and the daily materialized view, then merges again later. On a self-hosted 2.4.0 install with ~200 executions a minute, that kept ClickHouse at 50–200% of three cores after #13874 had already stopped the system logs. 1.9.x did not have this: it aggregated in memory and wrote every 20 seconds.Timer::afterwrites it 5 seconds after it opens, and the next message opens a new batch.Accumulatorper minute of event time. A folded event keeps the earliest time it absorbed, so a single accumulator would move events past a minute boundary into the earlier minute, or the earlier hour or day at the turn of one. A batch that crosses a minute is written as two inserts in the same flush.Coroutine\run(), which returns only once nothing is pending, so a tick would stop the worker from ever exiting. A pending one-shot holds it only until it fires, which means a stopping worker writes its last batch. 5 seconds keeps that under Docker's default 10-second stop timeout.Trade-offs: usage reaches ClickHouse up to 5 seconds later, a killed worker loses up to 5 seconds of usage (writes were already best-effort and never retried), and events folded into one row take the earliest time within their minute, at most 5 seconds early.
Test Plan
Ran a second worker container (
worker stats-usage) on the local stack's network against its ClickHouse, sent 60 requests toGET /v1/localeover 12 seconds, and counted inserts from that container insystem.query_logand new parts insystem.part_log. The stack's own worker took the other half of the messages.events/events_dailymainmain: 30network.requestsand 8190 bytes ofnetwork.inboundin both runs. Identical requests fold into one row with the value summed, so rows written dropped from 90 to 9.docker stopwith the default timeout, sent right after 10 requests: the worker wrote the pending batch and exited with code 0 after 5 seconds.ClickHouse CPU. Same setup, 16 requests a second for 3 minutes (about 8 messages a second reach the test worker, roughly the insert rate in the community report), then 60 seconds for merges to settle. CPU is the ClickHouse container's cgroup
usage_usecover the 4 minutes; parts and merge CPU are fromsystem.part_logfor the usage tables. Run order main, this PR, main.mainmainagainAbove idle, the load costs
main0.47–0.67 cores and this PR 0.03. The worker's own CPU is 0.013 cores in every run. This ran on Docker Desktop on Apple silicon; an older VPS core does the same work more slowly.Related PRs and Issues
Checklist