diff --git a/src/lib/db/client-metrics-store-v2.ts b/src/lib/db/client-metrics-store-v2.ts index 83ff90e50e..796c7a79f6 100644 --- a/src/lib/db/client-metrics-store-v2.ts +++ b/src/lib/db/client-metrics-store-v2.ts @@ -179,11 +179,21 @@ export class ClientMetricsStoreV2 implements IClientMetricsStoreV2 { await this.db.raw(query); const variantRows = spreadVariants(metrics).map(toVariantRow); - if (variantRows.length > 0) { + + // Sort the rows to avoid deadlocks + const sortedVariantRows = variantRows.sort( + (a, b) => + a.feature_name.localeCompare(b.feature_name) || + a.app_name.localeCompare(b.app_name) || + a.environment.localeCompare(b.environment) || + a.variant.localeCompare(b.variant), + ); + + if (sortedVariantRows.length > 0) { const insertVariants = this.db( TABLE_VARIANTS, ) - .insert(variantRows) + .insert(sortedVariantRows) .toQuery(); const variantsQuery = `${insertVariants.toString()} ON CONFLICT (feature_name, app_name, environment, timestamp, variant) DO UPDATE SET "count" = "client_metrics_env_variants"."count" + EXCLUDED.count`; await this.db.raw(variantsQuery);