Skip to content

fix(certificates): back off between issuance retries instead of a fixed interval - #13752

Closed
HarshMN2345 wants to merge 8 commits into
claude/certificates-bound-delayed-issuancefrom
claude/certificates-issuance-backoff
Closed

HarshMN2345 wants to merge 8 commits into
claude/certificates-bound-delayed-issuancefrom
claude/certificates-issuance-backoff

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Stacked on #13751 → #13573 → #13572 → #13571 → #13570. Merge in order; GitHub retargets automatically. The diff shown here is only this change.

This is task B from the support report: "these logs are uuuugly. too much spam. Let's say something like 'Retrying in X seconds/minutes.' And have a backoff like Kubernetes have."

What does this PR do?

A rule waiting on a certificate is retried once per APP_CERTIFICATE_GENERATION_LEASE (900 s) for as long as it stays that way, and every retry appends a line to the log the console shows the customer. The reported domains collected 19 hours of them. The lines are identical, so the log is worse than useless — the one thing you want to know, how long has this actually been going, is buried in a wall of the same sentence.

Each retry now waits twice as long as the one before it, from the lease period up to the attempt cap:

attempts wait cumulative
0 15 min 15 min
1 30 min 45 min
2 60 min 1 h 45
3 120 min 3 h 45
4 240 min 7 h 45

Five log lines over ~8 hours instead of ~31, and combined with #13751 the rule then fails with something actionable rather than continuing forever.

The scan query in Interval::generateCertificate() still selects on the shortest wait — Query::updatedBefore($expired) with the base lease — and the longer waits are held back inside the claim transaction:

$due = DatabaseDateTime::format(new DateTime(
    '-' . APP_CERTIFICATE_GENERATION_LEASE * (2 ** \min($certificate->getAttribute('attempts', 0), APP_LIMIT_CERTIFICATE_ATTEMPTS)) . ' seconds'
));
$since = empty($lease) ? $certificate->getAttribute('issueDate') : $lease;
// ...
|| (!empty($since) && new DateTime($since) >= new DateTime($due))

Holding it back in the claim rather than the query is deliberate: a per-row interval is not expressible as one updatedBefore filter, and the claim already re-reads every row under forUpdate and already has a $skipped path that costs nothing. The $processed ceiling added in #13573 counts enqueued jobs, so skipped rows do not consume the Let's Encrypt budget either.

Which clock the backoff measures from

This is the subtle part, and it took two corrections to get right.

The rule's own $updatedAt is not usable. A requested retry whose DNS validation fails bumps $updatedAt without spending an attempt, so a customer who retried too early and then fixed their DNS would sit out the whole accumulated delay — up to four hours — for a retry that used to take fifteen minutes.

The lease alone is also not enough. The worker writes 'updated' => $waiting ? $lease : null, so a rule left in certificate-generation-failed carries no lease at all. Keying only on the lease meant the guard never fired for those, and the main retry path kept the flat 900 s gate with no backoff whatsoever — the exact spam this PR exists to stop.

So the clock is the last issuance activity: the lease while a worker is waiting on the authority, otherwise the attempt it last reserved (certificates.issueDate, written when the attempt is reserved). Neither is touched by an unrelated write to the rule, and an explicit retry that passes validation clears the lease and resets attempts to 0, so it is served on the very next tick rather than serving out a backoff it did not earn.

The log line now names the wait it will actually take:

SSL certificate is being issued. Checking again in 30 minutes.

instead of repeating "We'll periodically check and update the status." It is computed from the same expression, at the one other place that knows the attempt count. I kept that duplicated rather than reaching across Tasks\Interval and Workers\Certificates for a shared helper — two occurrences of one arithmetic line is cheaper to read than the indirection, per the reuse guidance in AGENTS.md.

No new attribute, no new constant, no migration.

On reusing utopia-php/client's Backoff

It was suggested as prior art, and I read it — it is a PSR-18 retry decorator: it sleeps in-process between HTTP attempts inside one call. What is needed here is a schedule that survives process restarts and is evaluated by a different process (the scheduler) than the one that incremented the counter (the worker), against state in the database. Wiring the decorator into that would mean using its formula and none of its mechanism, so I took the formula shape (double each time, bounded) and left the class alone. Happy to be overruled if consistency across the codebase is worth more here than the fit.

Test Plan

tests/e2e/General/Certificates/IntervalTest.php, against a throwaway PostgreSQL schema:

  • testRetriesBackOffAsAttemptsAccumulate — two waiting rules, both with 2 spent attempts (so a 60-minute wait). The one whose lease is 30 minutes old is held back; the one at 90 minutes is claimed and enqueued.
  • testAFailedIssuanceBacksOffFromItsLastAttempt — the same boundary for a failed rule, which carries no lease. Backs off from issueDate instead. Without the second clock this case has no backoff at all.
  • testAFreshFailureIsNotHeldBackByBackoff — a rule with nothing spent is still retried promptly, so the backoff cannot quietly start punishing the common case.

One existing test needed its fixture moved, with an inline comment:

  • testRecentExpiredWorkDoesNotWaitUntilTheNextDay seeded -30 minutes, which is inside the 60-minute backoff its 2-attempt seed now earns. Moved to -90 minutes — still far inside the daily sweep this test is actually about, but outside the retry interval, so it tests the thing its name claims.

I checked the remaining seeds in the file: they carry neither a lease nor an issueDate, so they keep the flat gate and are unaffected.

$ composer lint src/Appwrite/Platform/Tasks/Interval.php src/Appwrite/Platform/Workers/Certificates.php tests/e2e/General/Certificates/IntervalTest.php
{"tool":"pint","result":"passed"}

Runs in Tests / E2E / General; skips locally without PostgreSQL.

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? — no API metadata changed.

…ed interval

A rule waiting on a certificate was retried once per lease period for as
long as it stayed that way. A certificate authority blocked on a DNS
record the domain owner has not added stays that way for hours, so the
rule collected one "still being issued" line every fifteen minutes --
dozens of identical lines in the log the console shows the customer.

Each retry now waits twice as long as the one before it, from the lease
period up to the attempt cap: 15, 30, 60, 120, then 240 minutes. The scan
query still selects on the shortest wait, so the longer ones are held
back in the claim, where a skipped rule already costs nothing. The log
line names the wait it will actually take rather than repeating itself.
@greptile-apps

greptile-apps Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The retry behavior appears correct, but the implementation-coupled worker test violates an explicit repository testing requirement and must be replaced before merging.

Fix All in Claude CodeFindings

  1. P2 Test Checks Internal State ▶
Fix with agent prompt
### Issue 1
tests/e2e/General/Certificates/WorkerTest.php:434
This assertion only checks that the internal `issueDate` field changed. It can pass without showing that the next certificate retry is actually delayed, and it will fail if the same behavior is later implemented with a different clock. The repository requires tests to verify observable behavior rather than mirror implementation details, so this must be replaced with an observable scheduling assertion before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

This PR replaces fixed certificate issuance retries with bounded exponential backoff and measures failed retries from their last issuance activity.

  • Computes retry eligibility from the current attempt count and the latest lease or issuance timestamp.
  • Refreshes the backoff clock whenever the worker spends an attempt.
  • Reports the expected retry delay in customer-visible certificate logs.
  • Adds interval and worker coverage for accumulated retries, failed issuance, and fresh failures.

Reviews (6) · Last reviewed commit: "fix(certificates): move the backoff cloc..."

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing claude/certificates-bound-delayed-issuance (before) → claude/certificates-issuance-backoff (after).

Metric Before After Change
🚀 Requests/sec 193.52 192.76 ⚪ -0.4%
⏱️ Latency P50 89.48 ms 89.54 ms ⚪ +0.1%
⏱️ Latency P95 211.82 ms 212.6 ms ⚪ +0.4%
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 89.54 212.6 12,027 192.76 +0.78
Account 170.97 322.74 633 10.5 -8.39
TablesDB 87.51 168.7 6,541 106.99 +3.78
Storage 80.82 183.62 3,165 53.59 +1.38
Functions 123.34 265.02 1,688 29.4 +8.31

Top API waits (after)

API request Max wait (ms)
account.name.update 655.77
functions.create 467.21
storage.files.create 409.45
functions.variables.create 401.78
tablesdb.rows.delete 398.99

…mestamp

Keying the backoff off the rule's `$updatedAt` meant any write to the rule
restarted it. A manual retry whose DNS validation fails bumps `$updatedAt`
without resetting attempts, so a customer who retried too early and then
fixed their DNS would have waited out the whole accumulated delay -- up to
four hours -- for a retry that used to take fifteen minutes. Greptile
caught it.

Scale how long the lease is honoured instead. The lease is written by
issuance and by nothing else, so an unrelated write to the rule cannot
restart the delay, and an explicit retry -- which clears the lease -- is
served on the next tick rather than serving out a backoff it did not earn.
@HarshMN2345
HarshMN2345 force-pushed the claude/certificates-bound-delayed-issuance branch from be12d7b to 19b53ff Compare September 18, 2026 09:06
@HarshMN2345
HarshMN2345 force-pushed the claude/certificates-issuance-backoff branch from b0af40f to 50f9d81 Compare September 18, 2026 09:06
… one

Keying the backoff on the lease alone meant it never applied to the case
it was written for. The worker clears the lease on any completion that is
not a wait, so a rule left in certificate-generation-failed carries none,
the guard never fired, and those retries stayed on the flat lease-period
gate -- no backoff at all on the main retry path.

Measure from the last issuance activity instead: the lease while a worker
waits on the authority, otherwise the attempt it last reserved. The rule's
own $updatedAt still is not used, because a requested retry whose DNS
check fails bumps it without spending an attempt and would serve out a
delay it never earned.
The scheduler measures its backoff from issueDate, but only the reservation
before a provider call was writing it. A counted wait and a failure caught
before reservation both spend an attempt and left it behind, so a rule that
polled pending a few times and then failed computed a long delay from an
old date and came due immediately -- the backoff bypassed on exactly the
path it was added for. Greptile caught it.

Stamp it wherever attempts is spent, so the count and the clock cannot
drift apart. Nothing else reads the attribute, so it now means the last
attempt rather than the last reservation.
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