Skip to content
TypeScript

fix(server): telemetry keeps a failed batch for 30 minutes, not 1.5 (#25474)

Theo Browne576a40fa530d
diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts
index 1cc66be7b3d..417841cb53e 100644
--- a/apps/server/src/telemetry/AnalyticsService.test.ts
+++ b/apps/server/src/telemetry/AnalyticsService.test.ts
@@ -1,6 +1,7 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -80,6 +81,24 @@ const respondWithStatus =
(request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status })));
+/**
+ * Answers 503 for `minutes` after the first send, then 204. `answers` holds each
+ * answer with its time in ms after the first send (the test clock runs on across tests).
+ */
+const failingFor = (minutes: number) => {
+ const answers: Array<{ readonly at: number; readonly status: number }> = [];
+ let firstSend: number | undefined;
+ const respond: Respond = (request) =>
+ Effect.flatMap(Clock.currentTimeMillis, (now) => {
+ firstSend ??= now;
+ const at = now - firstSend;
+ const status = at < minutes * 60_000 ? 503 : 204;
+ answers.push({ at, status });
+ return respondWithStatus(status)(request);
+ });
+ return { respond, answers };
+};
+
const recordTwentyEvents = Effect.gen(function* () {
const analytics = yield* AnalyticsService.AnalyticsService;
for (let index = 0; index < 20; index += 1) {
@@ -88,11 +107,12 @@ const recordTwentyEvents = Effect.gen(function* () {
});
/**
- * Runs `record` (20 events by default), then lets ten minutes of background
+ * Runs `record` (20 events by default), then lets `minutes` of background
* flushes run against a client that answers every send with `respond`.
* Returns the sent batches.
*/
-const sendForTenMinutes = (
+const sendFor = (
+ minutes: number,
respond: Respond,
record: Effect.Effect<
void,
@@ -137,7 +157,7 @@ const sendForTenMinutes = (
yield* Effect.gen(function* () {
yield* record;
- for (let second = 0; second < 600; second += 1) {
+ for (let second = 0; second < minutes * 60; second += 1) {
yield* TestClock.adjust("1 second");
}
}).pipe(Effect.provide(runtimeLayer));
@@ -147,7 +167,8 @@ const sendForTenMinutes = (
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
it.effect("client owner reports cannot use up the server's owner cap", () =>
Effect.gen(function* () {
- const batches = yield* sendForTenMinutes(
+ const batches = yield* sendFor(
+ 10,
respondWithStatus(204),
Effect.gen(function* () {
const analytics = yield* AnalyticsService.AnalyticsService;
@@ -170,6 +191,36 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
}),
);
+ it.effect("keeps a failed batch through a 20-minute outage and sends it once after", () =>
+ Effect.gen(function* () {
+ const ingest = failingFor(20);
+ const batches = yield* sendFor(40, ingest.respond);
+ const statuses = ingest.answers.map(({ status }) => status);
+ assert.equal(statuses.at(-1), 204);
+ assert.equal(statuses.filter((status) => status === 204).length, 1);
+ const sentUuids = new Set(batches.map((batch) => batch.map(({ uuid }) => uuid).join()));
+ assert.equal(sentUuids.size, 1);
+ assert.equal(batches[0]?.length, 20);
+ }),
+ );
+
+ it.effect("drops a batch that keeps failing for 30 minutes", () =>
+ Effect.gen(function* () {
+ const ingest = failingFor(Infinity);
+ yield* sendFor(60, ingest.respond);
+ const lastSend = ingest.answers.at(-1)?.at ?? 0;
+ assert.isAtLeast(lastSend, 30 * 60_000);
+ assert.isBelow(lastSend, 36 * 60_000);
+ }),
+ );
+
+ it.effect("drops a batch the endpoint rejects without sending it again", () =>
+ Effect.gen(function* () {
+ const batches = yield* sendFor(10, respondWithStatus(400));
+ assert.equal(batches.length, 1);
+ }),
+ );
+
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts
index 64c401c7bb4..582b0acafa5 100644
--- a/apps/server/src/telemetry/AnalyticsService.ts
+++ b/apps/server/src/telemetry/AnalyticsService.ts
@@ -32,6 +32,7 @@ interface BufferedAnalyticsEvent {
interface DeliveryState {
readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
readonly batchAttempts: number;
+ readonly firstFailedAt: number;
readonly failures: number;
readonly retryAt: number;
}
@@ -40,7 +41,10 @@ interface DeliveryState {
const FLUSH_INTERVAL_MS = 10_000;
// A hung send would hold the flush lock, and with it the shutdown flush.
const SEND_TIMEOUT = "10 seconds";
-const MAX_BATCH_ATTEMPTS = 5;
+// A failed batch is tried again until it has failed for this long. Ingest answers 503 when it
+// cannot store a batch, and a broken Cloudflare location can take about 5 minutes to fail over.
+// The waiting batch holds newer events back; `maxBufferedEvents` bounds them meanwhile.
+const MAX_BATCH_RETRY_MS = 30 * 60_000;
const RETRY_BASE_DELAY_MS = 2_000;
// Clients can report any number of owner ids; past this many per observer, new ones
// are not sent. Each observer has its own cap, so client reports never crowd out the
@@ -133,6 +137,7 @@ export const make = Effect.gen(function* () {
const deliveryRef = yield* Ref.make<DeliveryState>({
failedBatch: [],
batchAttempts: 0,
+ firstFailedAt: 0,
failures: 0,
retryAt: 0,
});
@@ -232,27 +237,47 @@ export const make = Effect.gen(function* () {
const sent = yield* Effect.result(sendBatch(batch));
if (Result.isSuccess(sent)) {
- yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 });
+ yield* Ref.set(deliveryRef, {
+ failedBatch: [],
+ batchAttempts: 0,
+ firstFailedAt: 0,
+ failures: 0,
+ retryAt: 0,
+ });
continue;
}
+ const now = yield* Clock.currentTimeMillis;
const failures = delivery.failures + 1;
const batchAttempts = delivery.batchAttempts + 1;
- const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
+ const firstFailedAt = delivery.batchAttempts === 0 ? now : delivery.firstFailedAt;
+ const retryAt = now + retryDelayMs(failures, yield* Random.next);
const error = sent.failure;
const rejected =
error._tag === "HttpClientError" &&
error.reason._tag === "StatusCodeError" &&
REJECTED_BATCH_STATUSES.has(error.reason.response.status);
- if (!rejected && batchAttempts < MAX_BATCH_ATTEMPTS) {
- yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
+ if (!rejected && now - firstFailedAt < MAX_BATCH_RETRY_MS) {
+ yield* Ref.set(deliveryRef, {
+ failedBatch: batch,
+ batchAttempts,
+ firstFailedAt,
+ failures,
+ retryAt,
+ });
yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
attempt: batchAttempts,
cause: error,
});
return;
}
- yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
+ yield* Ref.set(deliveryRef, {
+ failedBatch: [],
+ batchAttempts: 0,
+ firstFailedAt: 0,
+ failures,
+ retryAt,
+ });
yield* Effect.logWarning(
rejected
? "Dropped telemetry batch the endpoint rejected"