Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(brands): delete a brand's answers in batches on the server so large brands can be deleted (#991)

Gökhan Geyik1ebf69e6f97b
diff --git a/server/src/lib/brand-delete.js b/server/src/lib/brand-delete.js
new file mode 100644
index 000000000..26b481415
--- /dev/null
+++ b/server/src/lib/brand-delete.js
@@ -0,0 +1,68 @@
+/**
+ * Deleting a brand and everything under it.
+ *
+ * The web used to delete the brand row directly, as the signed-in user. The
+ * cascade reaches every answer the brand received and every citation row and
+ * shopping card under them, and on a brand of any size it outran the
+ * authenticated role's 8-second statement timeout: the delete was cancelled
+ * and the brand stayed. Here the answers go first, in batches that each fit
+ * comfortably in a statement, and the brand row — with what little is left
+ * under it — last.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+
+/** Answers deleted per statement, with their citation rows and shopping cards. */
+export const RESULT_BATCH = 2000;
+
+/** Brands being deleted right now, so a second click does not start a second run. */
+const inProgress = new Map();
+
+/**
+ * Deletes in batches until `deleteBatch` reports none left.
+ * @param {() => Promise<number>} deleteBatch - deletes one batch, returns how many it deleted
+ * @returns {Promise<number>} total deleted
+ */
+export async function drainInBatches(deleteBatch) {
+ let total = 0;
+ for (;;) {
+ const deleted = await deleteBatch();
+ total += deleted;
+ if (deleted === 0) return total;
+ }
+}
+
+async function run(brandId) {
+ const started = Date.now();
+ const results = await drainInBatches(async () => {
+ const { data, error } = await supabaseAdmin.rpc('delete_brand_results_batch', {
+ p_brand_id: brandId,
+ p_limit: RESULT_BATCH,
+ });
+ if (error) throw new Error(error.message);
+ return Number(data) || 0;
+ });
+
+ const { error } = await supabaseAdmin.from('brands').delete().eq('id', brandId);
+ if (error) throw new Error(error.message);
+
+ logger.info({ brandId, results, ms: Date.now() - started }, '[brands] deleted');
+}
+
+/**
+ * Starts deleting a brand, or returns the run already in progress for it.
+ * @returns {Promise<void>}
+ */
+export function deleteBrand(brandId) {
+ if (!inProgress.has(brandId)) {
+ const job = run(brandId)
+ .catch((err) => {
+ logger.error({ err, brandId }, '[brands] delete failed');
+ throw err;
+ })
+ .finally(() => inProgress.delete(brandId));
+ inProgress.set(brandId, job);
+ }
+ return inProgress.get(brandId);
+}
diff --git a/server/src/lib/brand-delete.test.js b/server/src/lib/brand-delete.test.js
new file mode 100644
index 000000000..2669e3f9f
--- /dev/null
+++ b/server/src/lib/brand-delete.test.js
@@ -0,0 +1,63 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const rpc = vi.fn();
+const eq = vi.fn();
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ rpc: (...args) => rpc(...args),
+ from: () => ({ delete: () => ({ eq: (...args) => eq(...args) }) }),
+ },
+}));
+
+const { RESULT_BATCH, deleteBrand, drainInBatches } = await import('./brand-delete.js');
+
+describe('drainInBatches', () => {
+ it('keeps deleting until a batch comes back empty', async () => {
+ const batches = [5, 5, 2, 0];
+ const deleteBatch = vi.fn(async () => batches.shift());
+ expect(await drainInBatches(deleteBatch)).toBe(12);
+ expect(deleteBatch).toHaveBeenCalledTimes(4);
+ });
+});
+
+describe('deleteBrand', () => {
+ it('deletes the answers in batches, then the brand row', async () => {
+ const left = [RESULT_BATCH, 10, 0];
+ rpc.mockImplementation(async () => ({ data: left.shift(), error: null }));
+ eq.mockResolvedValue({ error: null });
+
+ await deleteBrand('b1');
+
+ expect(rpc).toHaveBeenCalledTimes(3);
+ expect(rpc).toHaveBeenCalledWith('delete_brand_results_batch', {
+ p_brand_id: 'b1',
+ p_limit: RESULT_BATCH,
+ });
+ expect(eq).toHaveBeenCalledWith('id', 'b1');
+ });
+
+ it('runs one delete per brand however often it is asked', async () => {
+ rpc.mockReset();
+ let release;
+ rpc.mockImplementationOnce(
+ () => new Promise((resolve) => (release = () => resolve({ data: 0, error: null }))),
+ );
+ eq.mockResolvedValue({ error: null });
+
+ const first = deleteBrand('b2');
+ const second = deleteBrand('b2');
+ expect(second).toBe(first);
+ release();
+ await first;
+ expect(rpc).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves the brand row alone when a batch fails', async () => {
+ rpc.mockReset();
+ eq.mockReset();
+ rpc.mockResolvedValue({ data: null, error: { message: 'timeout' } });
+
+ await expect(deleteBrand('b3')).rejects.toThrow('timeout');
+ expect(eq).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/routes/brands.js b/server/src/routes/brands.js
new file mode 100644
index 000000000..a16e741e0
--- /dev/null
+++ b/server/src/routes/brands.js
@@ -0,0 +1,54 @@
+import { Router } from 'express';
+import supabaseAdmin from '../config/supabase.js';
+import { assertBrandAccess } from '../lib/access.js';
+import { deleteBrand } from '../lib/brand-delete.js';
+
+const router = Router();
+
+/**
+ * How long the request waits for the delete before answering that it is
+ * still running. Most brands are gone well within it; the largest take
+ * minutes, and the deletion carries on after the response.
+ */
+const WAIT_MS = 20_000;
+
+/**
+ * DELETE /api/brands/:id
+ * Deletes a brand and all its data. Admins only, as the brands delete policy
+ * allows. 200 when it is gone, 202 when it is still being deleted.
+ */
+router.delete('/:id', async (req, res) => {
+ try {
+ const brandId = req.params.id;
+ await assertBrandAccess(brandId, req.user.id);
+
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('role')
+ .eq('id', req.user.id)
+ .single();
+ if (profile?.role !== 'admin') {
+ return res.status(403).json({ error: 'Only admins can delete a brand.' });
+ }
+
+ const job = deleteBrand(brandId);
+ const outcome = await Promise.race([
+ job.then(() => 'deleted'),
+ new Promise((resolve) => setTimeout(() => resolve('pending'), WAIT_MS)),
+ ]);
+ // A delete that outlives the request must not surface as an unhandled
+ // rejection; brand-delete.js has already logged it.
+ job.catch(() => {});
+
+ return outcome === 'deleted'
+ ? res.json({ deleted: true })
+ : res.status(202).json({ deleted: false, pending: true });
+ } catch (error) {
+ req.log.error({ err: error }, 'delete brand error');
+ return res.status(error.status || 500).json({
+ error: error.status ? error.message : 'Failed to delete the brand.',
+ });
+ }
+});
+
+export default router;
diff --git a/server/src/routes/index.js b/server/src/routes/index.js
index 9c813bb08..e20475fc2 100644
--- a/server/src/routes/index.js
+++ b/server/src/routes/index.js
@@ -8,6 +8,7 @@ import topicRoutes from './topics.js';
import auditRoutes from './audits.js';
import reportRoutes from './reports.js';
import integrationRoutes from './integrations.js';
+import brandRoutes from './brands.js';
const router = Router();
@@ -20,6 +21,7 @@ router.use('/topics', topicRoutes);
router.use('/audits', auditRoutes);
router.use('/reports', reportRoutes);
router.use('/integrations', integrationRoutes);
+router.use('/brands', brandRoutes);
router.get('/health', (req, res) => {
res.json({ status: 'ok', user: req.user?.id });
diff --git a/supabase/migrations/00117_delete_brand_results_batch.sql b/supabase/migrations/00117_delete_brand_results_batch.sql
new file mode 100644
index 000000000..c6563a3a4
--- /dev/null
+++ b/supabase/migrations/00117_delete_brand_results_batch.sql
@@ -0,0 +1,34 @@
+-- Deleting a brand in batches.
+--
+-- A brand delete cascades to every answer it ever received, and from each
+-- answer to its citation rows and shopping cards. A brand with 15,000 answers
+-- carries well over 100,000 citation rows. Run as one statement under the
+-- authenticated role's 8-second statement timeout, the delete was cancelled
+-- every time, and the brand stayed.
+--
+-- The server now deletes a brand's answers in batches with this function,
+-- each batch a short statement of its own, and deletes the brand row once
+-- they are gone.
+
+create or replace function public.delete_brand_results_batch(
+ p_brand_id uuid,
+ p_limit integer default 2000
+)
+returns integer
+language plpgsql
+set search_path = public
+as $$
+declare
+ deleted integer;
+begin
+ delete from prompt_results
+ where id in (
+ select id from prompt_results where brand_id = p_brand_id limit p_limit
+ );
+ get diagnostics deleted = row_count;
+ return deleted;
+end;
+$$;
+
+revoke all on function public.delete_brand_results_batch(uuid, integer) from public, anon, authenticated;
+grant execute on function public.delete_brand_results_batch(uuid, integer) to service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index b4fadf2b1..5f6303824 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -13677,3 +13677,41 @@ revoke all on function public.opportunity_basket_metrics(uuid, uuid[], text[], t
grant execute on function public.opportunity_basket_metrics(uuid, uuid[], text[], text[], text[], date, date)
to service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00117_delete_brand_results_batch.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Deleting a brand in batches.
+--
+-- A brand delete cascades to every answer it ever received, and from each
+-- answer to its citation rows and shopping cards. A brand with 15,000 answers
+-- carries well over 100,000 citation rows. Run as one statement under the
+-- authenticated role's 8-second statement timeout, the delete was cancelled
+-- every time, and the brand stayed.
+--
+-- The server now deletes a brand's answers in batches with this function,
+-- each batch a short statement of its own, and deletes the brand row once
+-- they are gone.
+
+create or replace function public.delete_brand_results_batch(
+ p_brand_id uuid,
+ p_limit integer default 2000
+)
+returns integer
+language plpgsql
+set search_path = public
+as $$
+declare
+ deleted integer;
+begin
+ delete from prompt_results
+ where id in (
+ select id from prompt_results where brand_id = p_brand_id limit p_limit
+ );
+ get diagnostics deleted = row_count;
+ return deleted;
+end;
+$$;
+
+revoke all on function public.delete_brand_results_batch(uuid, integer) from public, anon, authenticated;
+grant execute on function public.delete_brand_results_batch(uuid, integer) to service_role;
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
index 7bda18ea3..96c0d6d71 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
@@ -126,9 +126,13 @@ export default function BrandSettingsPage({ params }: PageProps) {
<TabsContent value="danger">
<DangerTab
brand={brand}
- onDelete={async () => {
+ onDelete={async (pending) => {
removeBrand(brand.id);
- toast.success('Brand deleted.');
+ toast.success(
+ pending
+ ? 'Deleting the brand. It has a lot of data, so this can take a few minutes.'
+ : 'Brand deleted.',
+ );
router.push('/dashboard/brands');
}}
/>
@@ -938,7 +942,13 @@ function TrackingTab({ brand }: { brand: Brand }) {
// ─── Danger Tab ───────────────────────────────────────────────────────────────
-function DangerTab({ brand, onDelete }: { brand: Brand; onDelete: () => Promise<void> }) {
+function DangerTab({
+ brand,
+ onDelete,
+}: {
+ brand: Brand;
+ onDelete: (pending: boolean) => Promise<void>;
+}) {
const t = useTranslations('brands');
const [confirmValue, setConfirmValue] = useState('');
const [isDeleting, setIsDeleting] = useState(false);
@@ -949,8 +959,13 @@ function DangerTab({ brand, onDelete }: { brand: Brand; onDelete: () => Promise<
if (!canDelete) return;
setIsDeleting(true);
try {
- await deleteBrand(brand.id);
- await onDelete();
+ const result = await deleteBrand(brand.id);
+ if ('error' in result) {
+ toast.error(result.error);
+ setIsDeleting(false);
+ return;
+ }
+ await onDelete(Boolean(result.pending));
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to delete brand.');
setIsDeleting(false);
diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.ts
index 3e45da2a3..ebe1ec721 100644
--- a/web/src/lib/actions/brand.ts
+++ b/web/src/lib/actions/brand.ts
@@ -5,6 +5,7 @@ import { revalidatePath } from 'next/cache';
import { getOrgPlan } from '@/lib/guards/plan-guard';
import { isWithinLimit } from '@/config/plans';
import { slugify } from '@/lib/slug';
+import { API_BASE_URL } from '@/config/api';
import type { Brand, BrandDomain } from '@/types';
function mapDomainRow(d: Record<string, unknown>): BrandDomain {
@@ -195,13 +196,37 @@ export async function updateBrand(id: string, updates: UpdateBrandInput): Promis
);
}
-export async function deleteBrand(id: string): Promise<void> {
+/**
+ * Deletes a brand through the server, which removes its answers in batches
+ * before the brand row: in one statement, a brand of any size outran the
+ * database's 8-second limit for signed-in requests and was never deleted.
+ *
+ * `pending` means the server is still deleting a large brand; it finishes on
+ * its own within minutes. Failures are returned rather than thrown, since a
+ * thrown server-action error reaches the browser without its message.
+ */
+export async function deleteBrand(
+ id: string,
+): Promise<{ deleted: boolean; pending?: boolean } | { error: string }> {
const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { error: 'Not authenticated' };
+
+ const res = await fetch(`${API_BASE_URL}/api/brands/${id}`, {
+ method: 'DELETE',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ });
+ const body = (await res.json().catch(() => ({}))) as {
+ deleted?: boolean;
+ pending?: boolean;
+ error?: string;
+ };
+ if (!res.ok) return { error: body.error || 'Failed to delete the brand.' };
- const { error } = await supabase.from('brands').delete().eq('id', id);
-
- if (error) throw new Error(error.message);
revalidatePath('/dashboard/brands');
+ return { deleted: Boolean(body.deleted), pending: Boolean(body.pending) };
}
/**