Skip to content

fix: batch usage writes across messages - #14291

Merged
HarshMN2345 merged 5 commits into
mainfrom
fix/usage-batch-writes
Oct 9, 2026
Merged

HarshMN2345 merged 5 commits into
mainfrom
fix/usage-batch-writes

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

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 Accumulator for every queue message and flushed it before returning, so every API request and function execution became its own INSERT into projects_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.

  • Messages now fold into one batch per worker process. A one-shot Timer::after writes it 5 seconds after it opens, and the next message opens a new batch.
  • The batch holds one Accumulator per 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.
  • The batch is detached before the insert, so messages handled while the insert is in flight start the next batch instead of landing in one already sent.
  • It is a one-shot timer rather than a tick. The worker runs inside 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 to GET /v1/locale over 12 seconds, and counted inserts from that container in system.query_log and new parts in system.part_log. The stack's own worker took the other half of the messages.

Messages Inserts New parts in events / events_daily
main 30 30 30 / 30
this PR ~30 3 3 / 3
  • Summed totals match main: 30 network.requests and 8190 bytes of network.inbound in both runs. Identical requests fold into one row with the value summed, so rows written dropped from 90 to 9.
  • docker stop with the default timeout, sent right after 10 requests: the worker wrote the pending batch and exited with code 0 after 5 seconds.
  • A batch sent across 10:22:00 was written as two inserts at 10:22:01: 7 requests at 10:21:56 and 7 at 10:22:00–10:22:01, each in its own minute.
  • Pint and PHPStan pass on the changed file.

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_usec over the 4 minutes; parts and merge CPU are from system.part_log for the usage tables. Run order main, this PR, main.

ClickHouse cores (avg) Inserts Parts created Merges Merge CPU
idle 0.12 – – – –
main 0.59 2,368 4,396 879 38.3 s
this PR 0.15 36 72 14 0.9 s
main again 0.79 2,365 3,992 1,124 52.9 s

Above idle, the load costs main 0.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

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

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.
@luxor-code-review

luxor-code-review Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

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 · unchanged line

// 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->accumulator and drops it after a single flush attempt, so when $accumulator->flush() returns false or throws, the buffered entries are never retried (src/Appwrite/Platform/Workers/StatsUsage.php:148-163). Accumulator::flush() is built to retain unwritten entries for retry on the next flush, and since successfully written entries are already removed from its buffer, retrying cannot duplicate rows — the comment at src/Appwrite/Platform/Workers/StatsUsage.php:160-161 claiming a deduplication key is required misstates that contract. Because the whole window now folds into one batch, a transient ClickHouse failure silently loses up to 5 seconds of usage metrics for every project at once.


This PR reworks the stats-usage worker to accumulate metrics in an Accumulator and flush them to ClickHouse every 5 seconds via a Swoole timer, replacing the previous per-message flush. This substantially reduces insert pressure at the cost of a small buffering window.

Files Change
src/Appwrite/Platform/Workers/StatsUsage.php Batch accumulated usage metrics and flush them on a 5s Timer::after instead of per message; on flush failure the detached batch is dropped rather than retried.

Reviewed commit: 14eecfa

@ghost

ghost commented Oct 9, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental change addresses the previously reported time-bucket issue, and I found no new defects in these changes.

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.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 1
File Change
src/Appwrite/Platform/Workers/StatsUsage.php Buffers usage metrics in per-minute accumulators and flushes each open accumulator when the one-shot batch timer fires.
✅ Fixed since the last review · 1
  • Keep batches from merging across time buckets · src/Appwrite/Platform/Workers/StatsUsage.php:73

Reviewed the commits since 427819c · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

32 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (17)
  • php.appwrite.permissive-write-permission (8)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/usage-batch-writes (after).

Metric Before After Change
🚀 Requests/sec 210.67 213.28 ⚪ +1.2%
⏱️ Latency P50 81.67 ms 80.51 ms ⚪ -1.4%
⏱️ Latency P95 189.91 ms 189.64 ms ⚪ -0.1%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 80.51 189.64 13,509 213.28 -0.26
Account 154.2 294.5 711 11.77 +4.81
TablesDB 77.24 138.89 7,347 118.09 -10.79
Storage 75.45 164.89 3,555 59.07 +5.05
Functions 118.44 245.11 1,896 32.13 +1.8

Top API waits (after)

API request Max wait (ms)
account.name.update 557.94
account.prefs.update 415.39
functions.create 409.12
functions.delete 386.61
functions.variables.update 384.11

HarshMN2345 and others added 4 commits October 9, 2026 15:35
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.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@HarshMN2345
HarshMN2345 merged commit 9ee9b8d into main Oct 9, 2026
59 of 60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant