Build a GAQL Script for Sudden CPC Spike Alerts

Learn how to build a production GAQL script to detect sudden CPC spikes and search term surges in Google Ads before budget leaks drain your account.

By AdTurbo Team · 2026-10-20

A sudden cost-per-click surge can quietly drain your daily budget before lunchtime. If an auction heats up, a competitor launches an aggressive Target Impression Share campaign, or Google's Smart Bidding algorithms test aggressive upward bids on loose broad match queries, your average CPC on critical search terms can double or triple overnight.

Catching these cost spikes manually inside the web interface is nearly impossible. Standard reporting dashboards often mask term-level volatility behind broad campaign-level averages. By the time you notice your overall blended CPA rising in a weekly review, hundreds or thousands of dollars have evaporated.

To protect your margins, you need an automated watchdog. This guide shows you how to design, write, and deploy a Google Ads Query Language (GAQL) script that runs on schedule, compares granular search-term performance across dynamic time horizons, and sends instant alerts whenever a search term experiences a sudden 100%+ CPC surge.

The Economics of CPC Surges: Why Search Terms Double Overnight

Google Ads operates on dynamic second-price (and increasingly algorithmic threshold) auctions. While advertisers set target metrics at the campaign or ad group level, auction pricing fluctuates on the individual search-term layer.

Smart Bidding Volatility and Auction Dynamics

When Smart Bidding algorithms like Target CPA or Maximize Conversions detect high-intent signals (such as time of day, location, or audience affinity), they can push bids dramatically higher for specific auctions. If multiple advertisers run automated bidding strategies targeting the same demographic pocket simultaneously, auction clearing prices skyrocket.

Furthermore, when broad match or phrase match queries trigger new search terms, Google lacks historical conversion data for that specific string in your account. The bidding engine often aggressively bids upward to gauge conversion probability. If the search term fails to convert, you are left with exorbitant click fees.

The Hidden Waste: How 2x CPC Distorts Target ROAS and CPA

When a single high-volume search term moves from a $3.50 average CPC to $7.80, your unit economics fracture. If your historical conversion rate is 5%, a $3.50 CPC yields a $70 CPA. At $7.80 per click, that same conversion costs $156. If your target CPA is $85, that single query puts your entire ad group underwater.

To understand why these structural price hikes occur across entire verticals, review our breakdown on why Google Ads is so expensive. Left unchecked, single-term anomalies cause broad budget exhaustion, preventing high-performing, stable keywords from showing.

Background: Understanding GAQL and Script Architecture

To build a reliable automated monitor, you must understand how Google Ads Scripts interact with account data following the sunset of legacy AdWords Query Language (AWQL).

The Shift from AWQL to GAQL

Google modernised its reporting infrastructure by replacing AWQL with the Google Ads Query Language (GAQL). Unlike the legacy syntax, GAQL queries mimic SQL syntax more closely and query against specific resources in the Google Ads API schema.

In GAQL, metrics, segments, and resource attributes cannot be arbitrarily combined. Every query must respect resource boundaries. For search term analysis, the core resource is searchtermview.

The searchtermview Resource and Segment Limitations

The searchtermview resource provides historical performance metrics for actual queries that triggered your ads. However, it imposes specific operational constraints in Google Ads Scripts:

1. Data Freshness: Search term data can lag real-time clicks by a few hours. A sudden CPC spike script cannot alert you within seconds of a click, but it can catch intraday or day-over-day surges reliably.

2. Privacy Thresholds: Google strips low-volume queries from the search terms view. Only search terms that meet minimum query thresholds appear in the report.

3. Field Selection: You query metrics.averagecpc, metrics.clicks, metrics.costmicros, and searchtermview.searchterm. Remember that in the API, currency values are represented in micros (where 1,000,000 micros = $1.00).

For a broader look at interrogating this resource manually, read our search terms report guide.

The "Sudden Impact" Anomaly Detection Protocol: How It Works

Detecting a real anomaly requires more than looking for a high cost-per-click. If a term has one click at $10.00 compared to a historical average of $4.00, it might simply be an outlier auction rather than a systematic price doubling. We need a systematic protocol that eliminates small-sample noise.

Mathematical Baseline: Moving Averages vs. Fixed Thresholds

A rigid threshold (such as "alert if CPC $10") fails because different search terms naturally operate at different bid floors. A high-intent commercial term might normally cost $18, while an informational query costs $2.

Our detection script uses a rolling moving average baseline:

• Baseline Window: Previous 14 days (excluding the current evaluation window).

• Evaluation Window: Yesterday or the last 48 hours.

• Spike Trigger Condition: Current Average CPC = (Baseline Average CPC 2.0) AND Current Clicks = Minimum Click Threshold.

Baseline Average CPC = Baseline Cost / Baseline Clicks

Current Average CPC = Current Cost / Current Clicks

CPC Delta Ratio = Current Average CPC / Baseline Average CPC

If the CPC Delta Ratio is greater than or equal to 2.0, the query flags as an anomaly.

Dealing with Small Sample Noise and Statistical Significance

False positives ruin script reliability. If a search term generates 1 click for $6.00 after averaging $3.00 on 2 clicks over two weeks, sending an emergency alert wastes engineering and optimization time.

To guarantee statistical relevance, apply two filters:

• Minimum Baseline Clicks: The query must have recorded at least 10 clicks during the 14-day baseline period.

• Minimum Current Clicks: The query must have accumulated at least 5 clicks in the evaluation window.

| Feature | Manual UI Review | Standard Automated Rules | Custom GAQL Anomaly Script |

| :--- | :--- | :--- | :--- |

| Detection Granularity | Aggregate ad group / keyword | Campaign or Keyword level only | Exact search-term level |

| Dynamic Comparison | Manual visual comparison | Static thresholds (e.g., CPC $X) | Relative baseline comparison (e.g., 2x baseline) |

| Execution Schedule | Human dependent (weekly/monthly) | Hourly / Daily | Hourly / Daily via script schedule |

| Statistical Filters | Intuitive / subjective | Extremely limited | Enforces sample size parameters |

| Notification Channel | None (in-platform only) | Email only | Slack, Google Chat, or Webhook |

Prerequisites and Environment Setup

Before executing the script inside your account, prepare your environment and access permissions.

Script Permissions, Runtime Limits, and Cookies / Auth

Google Ads Scripts execute within the Google cloud infrastructure using your active user authentication. Ensure your browser allows the appropriate authorization cookies when opening the Scripts editor in the Google Ads UI (Tools & Settings Bulk Actions Scripts). If 3rd-party cookies are blocked or your session expires, script authorization tokens will fail to generate.

Keep script operational constraints in mind:

• Single-account scripts have a 30-minute maximum execution timeout.

• Scripts query up to 50,000 rows per GAQL selector iterator.

• Script authorization requires granting read/write permissions to Google Sheets and external network fetches (UrlFetchApp) if sending webhooks.

Configuring Notification Endpoints: Slack or Google Chat

While email alerts work, high-priority notifications belong in a collaborative channel. We will configure an incoming webhook for Slack or Google Chat. When a sudden CPC surge occurs, the script payloads JSON directly into your triage channel.

Step-by-Step Implementation: Building the GAQL Script

Below is the complete production-grade script. It executes two GAQL queries: one for the 14-day baseline period and one for the recent evaluation window. It joins the datasets in memory by searchterm, calculates the percentage change in CPC, filters for volume requirements, and fires an alert.

The Full Production-Ready Google Ads Script Code

Paste this code into your Google Ads Script editor:

javascript

/

• GAQL Search Term Sudden CPC Surge Anomaly Detector

• Detects search terms where recent average CPC has doubled (= 100% increase)

• compared to a historical 14-day baseline.

/

const CONFIG = {

// Thresholds

CPCMULTIPLIERTHRESHOLD: 2.0, // 2.0 = 100% increase (doubling)

MINBASELINECLICKS: 10,

MINCURRENTCLICKS: 5,

// Lookback Configuration

BASELINEDAYS: 14,

CURRENTDAYS: 2, // Last 2 days including today or yesterday

// Notifications

WEBHOOKURL: 'https://hooks.slack.com/services/YOUR/WEBHOOK/URL', // Leave empty to disable webhook

NOTIFICATIONEMAIL: '[email protected]', // Leave empty to disable email

// Account Details for Alert Context

ACCOUNTNAME: AdsApp.currentAccount().getName(),

ACCOUNTID: AdsApp.currentAccount().getCustomerId()

};

function main() {

Logger.log('Starting GAQL CPC Surge Analysis for ' + CONFIG.ACCOUNTNAME);

const baselineData = getBaselineMetrics();

const currentData = getCurrentMetrics();

const anomalies = detectSurges(baselineData, currentData);

if (anomalies.length 0) {

Logger.log('Identified ' + anomalies.length + ' search terms with sudden CPC doubling.');

notifyTeam(anomalies);

} else {

Logger.log('No abnormal CPC surges detected.');

}

}

/

• Queries historical baseline metrics (previous 14 days, excluding last 2 days)

/

function getBaselineMetrics() {

const terms = {};

// Date calculation: 16 days ago to 2 days ago

const dateRange = getDateRangeString(CONFIG.BASELINEDAYS + CONFIG.CURRENTDAYS, CONFIG.CURRENTDAYS);

const query =

SELECT

searchtermview.searchterm,

metrics.clicks,

metrics.costmicros,

metrics.averagecpc

FROM searchtermview

WHERE

segments.date BETWEEN '${dateRange.startDate}' AND '${dateRange.endDate}'

AND metrics.clicks = ${CONFIG.MINBASELINECLICKS}

;

const report = AdsApp.search(query);

while (report.hasNext()) {

const row = report.next();

const searchTerm = row.searchTermView.searchTerm;

const clicks = parseInt(row.metrics.clicks, 10);

const cost = parseFloat(row.metrics.costMicros) / 1000000;

const avgCpc = clicks 0 ? cost / clicks : 0;

terms[searchTerm] = {

clicks: clicks,

cost: cost,

avgCpc: avgCpc

};

}

return terms;

}

/

• Queries recent evaluation window metrics (last 2 days)

/

function getCurrentMetrics() {

const terms = {};

const dateRange = getDateRangeString(CONFIG.CURRENTDAYS, 0);

const query =

SELECT

searchtermview.searchterm,

campaign.name,

metrics.clicks,

metrics.costmicros,

metrics.averagecpc

FROM searchtermview

WHERE

segments.date BETWEEN '${dateRange.startDate}' AND '${dateRange.endDate}'

AND metrics.clicks = ${CONFIG.MINCURRENTCLICKS}

;

const report = AdsApp.search(query);

while (report.hasNext()) {

const row = report.next();

const searchTerm = row.searchTermView.searchTerm;

const campaignName = row.campaign.name;

const clicks = parseInt(row.metrics.clicks, 10);

const cost = parseFloat(row.metrics.costMicros) / 1000000;

const avgCpc = clicks 0 ? cost / clicks : 0;

// Aggregate if same search term appears across multiple campaigns

if (!terms[searchTerm]) {

terms[searchTerm] = {

campaigns: [campaignName],

clicks: clicks,

cost: cost,

avgCpc: avgCpc

};

} else {

terms[searchTerm].campaigns.push(campaignName);

terms[searchTerm].clicks += clicks;

terms[searchTerm].cost += cost;

terms[searchTerm].avgCpc = terms[searchTerm].cost / terms[searchTerm].clicks;

}

}

return terms;

}

/

• Compares baseline and current data sets to isolate spikes

/

function detectSurges(baseline, current) {

const surges = [];

for (const term in current) {

if (baseline[term]) {

const baseCpc = baseline[term].avgCpc;

const currCpc = current[term].avgCpc;

const multiplier = currCpc / baseCpc;

if (multiplier = CONFIG.CPCMULTIPLIERTHRESHOLD) {

surges.push({

term: term,

campaigns: current[term].campaigns.join(', '),

baselineCpc: baseCpc.toFixed(2),

currentCpc: currCpc.toFixed(2),

multiplier: multiplier.toFixed(2),

currentClicks: current[term].clicks,

currentCost: current[term].cost.toFixed(2)

});

}

}

}

return surges;

}

/

• Dispatches alerts via Webhook and/or Email

/

function notifyTeam(anomalies) {

let messageText = CPC Surge Warning: Sudden Doubling Detected\nAccount: ${CONFIG.ACCOUNTNAME} (${CONFIG.ACCOUNTID})\n\n;

anomalies.forEach(item = {

messageText += • "${item.term}" in [${item.campaigns}]\n;

messageText += Baseline CPC: ${item.baselineCpc} - Current CPC: ${item.currentCpc} (${item.multiplier}x surge)\n;

messageText += Recent Volume: ${item.currentClicks} clicks | Spend: ${item.currentCost}\n\n;

});

// Webhook Delivery

if (CONFIG.WEBHOOKURL && CONFIG.WEBHOOKURL.startsWith('http')) {

const payload = JSON.stringify({ text: messageText });

UrlFetchApp.fetch(CONFIG.WEBHOOKURL, {

method: 'post',

contentType: 'application/json',

payload: payload,

muteHttpExceptions: true

});

Logger.log('Webhook dispatched successfully.');

}

// Email Delivery

if (CONFIG.NOTIFICATIONEMAIL && CONFIG.NOTIFICATIONEMAIL.includes('@')) {

MailApp.sendEmail({

to: CONFIG.NOTIFICATIONEMAIL,

subject: 🚨 CPC Spike Alert: Search Terms Doubled in ${CONFIG.ACCOUNTNAME},

body: messageText.replace(/\/g, '')

});

Logger.log('Notification email dispatched.');

}

}

/

• Helper utility to calculate YYYY-MM-DD date boundaries

/

function getDateRangeString(daysBackStart, daysBackEnd) {

const now = new Date();

const start = new Date(now.getTime() - (daysBackStart 24 60 60 1000));

const end = new Date(now.getTime() - (daysBackEnd 24 60 60 1000));

return {

startDate: Utilities.formatDate(start, AdsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd'),

endDate: Utilities.formatDate(end, AdsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd')

};

}

Query Nuances and Currency Conversion

Notice how the script handles financial data. The raw field metrics.costmicros returns costs scaled by 1,000,000. If you query metrics.averagecpc, it returns a rounded micro-integer. To maintain mathematical precision across small click volumes, our script calculates the exact weighted average CPC by taking cost / clicks after converting micros to account currency units.

This prevents rounding errors where micro-conversions might incorrectly inflate low-cost terms.

How to Schedule an Automated Event and Execution Frequency

Once the script is saved and authorized, you must establish an automated execution schedule so alerts fire without human intervention.

Daily vs. Hourly Execution Schedules

Inside the Google Ads Scripts interface:

1. Navigate to Scripts in your Google Ads account.

2. Hover over your saved script and click Create Schedule in the Frequency column.

3. Select Daily and choose an early morning execution window (e.g., between 6:00 AM and 8:00 AM in your account's local time zone).

Running this specific script hourly is generally counterproductive. Because searchtermview updates with slight latency throughout the day, running it every 60 minutes rarely produces enough statistical sample size (unless your account spends tens of thousands of dollars per day). A daily morning run comparing the past 48 hours to the preceding two weeks provides reliable signal without alert fatigue.

Handling Script Execution Timeouts and Scaled Accounts

If your account manages millions of search terms annually, the AdsApp.search call might encounter memory pressure or approach the 30-minute runtime limit. If your account runs at massive enterprise scale, apply these modifications:

• Add a cost threshold to the WHERE clause: AND metrics.costmicros = 10000000 ($10 minimum spend).

• Restrict queries to active campaigns: AND campaign.status = 'ENABLED'.

• Split execution by campaign naming conventions or run individual scripts across dedicated campaign clusters.

Regular script health checks should form part of your broader process. Use our Google Ads optimization checklist to ensure automated alerts integrate cleanly into your operating cadence.

Incident Response: What to Do When a CPC Spike Alert Fires

Receiving an alert that a high-volume search term doubled in CPC requires swift, systematic triage. Do not blindly shut down the keyword or add a negative without following a root-cause checklist.

[Alert Fires: CPC = 2x Baseline]

│

▼

Check Search Term Intent Match

├── Irrelevant query? ──────► Add Exact Negative Keyword Immediately

└── High-intent core query?

│

▼

Check Auction Insights Report

├── New aggressive competitor? ──► Evaluate Impression Share & Position Loss

└── Competitor bids stable?

│

▼

Check Campaign Bidding Strategy Changes

├── Target CPA tightened or relaxed recently?

└── Smart Bidding testing wide query matching? ──► Apply Ad Group Max CPC Cap

1. Identify Search Query Relevance

Check whether the triggering query represents true commercial intent or a mismatched phrase expansion. If an ad group targeting b2b warehouse management software suddenly spent $45/click on warehouse inventory jobs near me, immediately add jobs as an exact or phrase negative keyword.

2. Inspect the Auction Insights Report

If the spike occurred on your exact target query (e.g., enterprise crm platform), review your Auction Insights tab for the last 48 hours. Look for:

• A competitor whose Outranking Share or Impression Share jumped dramatically.

• A new entrant bidding aggressively to capture market share.

If competitor aggression drove the spike, your conversion rate may remain consistent, but your profitability drops. You will need to decide whether to match bids or lower campaign targets to let the competitor burn through their promotional testing budget.

3. Evaluate Smart Bidding Bid Ceilings

If you use Target CPA or Target ROAS without bid caps, Google's algorithm has license to bid whatever it deems necessary to secure a conversion. If an automated bidding model gets trapped in an aggressive feedback loop, consider setting a Maximum Bid Limit (available if you run a Portfolio Bid Strategy).

Placing a maximum CPC ceiling on portfolio bid strategies stops the algorithm from doubling bids during temporary liquidity squeezes in the ad exchange.

Moving Beyond Standalone Scripts with AdTurbo

While custom GAQL scripts are invaluable for catching discrete search-term spikes, maintaining custom JavaScript across multiple accounts presents long-term engineering overhead. Custom scripts break when API schemas evolve, they cannot autonomously adjust bids in complex multi-factor scenarios, and they require ongoing developer maintenance.

If you want institutional-grade anomaly detection combined with autonomous optimization, consider adopting dedicated Google Ads automation tools. AdTurbo ($149/mo, with a fully featured 7-day trial, credit card required) acts as a real-time account co-pilot. Instead of merely alerting you after clicks have already registered at double the price, AdTurbo continuously models auction volatility, catches search-query drift, and autonomously caps runaway bidding dynamics before budgets bleed.

Whether you deploy custom scripts or an end-to-end platform, having automated guardrails on search-term CPCs is essential for modern PPC management.

Related Guides

• How to Use the Google Ads Search Terms Report to Cut Wasted Spend

• Why Is Google Ads So Expensive? 7 Reasons (And How to Pay Less)

• Google Ads Optimization Checklist: 15 Things to Check Every Week

Frequently Asked Questions

Why does the script calculate CPC manually instead of using metrics.averagecpc?

While GAQL offers metrics.averagecpc, calculating CPC directly from metrics.costmicros divided by metrics.clicks ensures decimal precision. The native average CPC field can round intermediate values, leading to skewed comparisons when measuring small percentage shifts.

How far back should my baseline comparison go?

A 14-day baseline represents the sweet spot for search term analysis. A 7-day window is frequently distorted by weekend traffic fluctuations, while a 30-day window often masks recent bidding changes or seasonal shifts that have altered auction floors.

Can this GAQL script automatically pause keywords that surge in CPC?

Yes, you can extend the script to mutate account entities via keyword.pause() or by pushing search terms to negative keyword lists. However, full automation on search terms is risky; alerting team members via webhook first prevents accidentally pausing high-converting brand or core revenue queries during expected seasonal sales spikes.

Will this script work across Performance Max and Shopping campaigns?

This script specifically queries searchtermview, which historically populates search queries triggered by Search campaigns and standard Shopping campaigns. For Performance Max campaigns, search term data is exposed primarily through the searchterminsight resource, which uses a different schema and requires cluster-based querying rather than row-by-row term metrics.