Articles Product Sign In Get started

Click Fraud Protection API: 2026 Developer Guide

· · Updated · 12 min read

What a click fraud protection API does, the 3 integration patterns (pre-click / pre-conversion / postback), code examples, and design pitfalls.

Abstract geometric composition in Kandinsky Bauhaus style — circles, triangles, and lines on warm paper background.

A click fraud protection API is a REST endpoint that accepts click context (IP, user agent, click ID, referrer, fingerprint) and returns a fraud verdict, typically in under 80ms. Engineering teams call it from three places: the landing page (pre-click), the conversion postback (pre-conversion), and the offline enrichment pipeline (post-conversion). The pattern lets you wire fraud detection into custom funnels, multi-tenant SaaS, and affiliate trackers without using a vendor’s dashboard. With Juniper Research projecting global ad-fraud losses to reach $172 billion by 2028, up from $84 billion in 2023, the API-first integration model is increasingly the default for engineering-led teams. [1]

This guide covers the three integration patterns, REST design expectations, working Node.js and curl code, what IP intelligence resolves under the hood, and the integration pitfalls that quietly break production. For the broader category context, see our click fraud protection pillar guide.

Key Takeaways
  • A click fraud protection API is for engineers who own the click handler. Dashboards work for Google Ads and Meta out of the box; APIs are necessary when you have custom funnels, multi-tenant rules, or affiliate routing logic.
  • Three integration patterns matter: pre-click (JS tag, synchronous), pre-conversion (S2S postback before counting), post-conversion (enrichment + refund evidence). Most production stacks use all three.
  • Latency budget is tight. Target p50 under 30ms, p99 under 80ms for in-funnel calls. Always implement a 200ms client-side timeout and fail open on errors.
  • IP intelligence is one of three signal layers, alongside behavioral analysis and fingerprinting. ASN classification + residential-proxy detection + threat intel covers ~70% of network-layer fraud. [2]
  • Build vs buy threshold: under 100M clicks per year, buy. Building means maintaining ASN data, proxy detection, and threat feeds with a 2-4 engineer team.

When do you need a click fraud API instead of a SaaS dashboard?

The decision between a click fraud protection API and a dashboard comes down to who owns the click handler. According to the MRC Invalid Traffic Detection Guidelines, real-time scoring requires per-click event data, and any team that controls its own funnel needs programmatic access to feed and read that data. [3] Dashboards are for ops users; APIs are for engineering teams who build the routing themselves.

Four scenarios where the API path is the only realistic option:

1. Custom funnel that does not fit a vendor UI

Vendor dashboards assume a standard funnel: ad click, landing page, conversion. If your funnel has multiple steps, conditional routing, A/B variants, or non-web touchpoints (in-app installs, voice, SMS callbacks), a dashboard can’t represent it. An API lets you score clicks at each meaningful checkpoint and feed the verdict into your own decision graph.

2. Multi-tenant SaaS where each tenant has different rules

If you’re running a platform where each customer has their own risk tolerance, an API lets you parameterize scoring per tenant. Tenant A might want aggressive blocking on residential proxies; Tenant B might want to allow them because their audience is privacy-conscious. A shared dashboard can’t express that without becoming a per-customer config nightmare.

3. Affiliate network with per-publisher scoring

Affiliate networks need to score clicks per publisher and feed verdicts back into their attribution chain. The S2S postback model is essentially an API contract, and dashboards don’t expose the integration depth you need. For the affiliate tracker pattern specifically, see our click fraud protection for affiliate trackers guide.

4. Custom attribution models

If you’ve built your own attribution (multi-touch, MMM, custom last-click windows), your fraud verdicts have to flow into your model, not a vendor’s reporting cube. An API delivers raw scores you can join, weight, and reshape inside your own data warehouse.

In the integration audits we’ve run, roughly 60% of engineering teams who started on a SaaS dashboard migrated to API integration within 18 months because the dashboard couldn’t represent their actual funnel. The other 40% stayed on dashboards because their funnel matched the vendor’s assumed shape.

What are the 3 click fraud API integration patterns?

Real-time click fraud detection APIs are called from three different points in the click lifecycle, and most production stacks use all three. The IAB OpenRTB specification describes a click as a chain of events that includes pre-auction signals, post-click landing, and post-conversion attribution, and a fraud API can sit at any of those points. [4]

Pattern 1: Pre-click (JS tag with synchronous scoring)

A JavaScript tag on the landing page fires on DOMContentLoaded, collects a click context (cookie ID, fingerprint, referrer, time on page so far), and calls the API synchronously. The verdict drives routing: pass to the real funnel, redirect to a holding page, or 204 the response.

  • Latency budget: p99 < 80ms (user is waiting)
  • Failure mode: fail open (don’t block legitimate users on a slow API)
  • Use cases: Google Ads, Meta Ads, programmatic display where you control the lander

Pattern 2: Pre-conversion (S2S postback before counting)

When a conversion fires (form submit, signup, purchase), your backend calls the fraud API with the original click context before crediting the conversion in your tracker. If the verdict is “fraud,” skip the postback to the ad network, don’t trigger affiliate payouts, and don’t enrich the lead for sales follow-up.

  • Latency budget: p99 < 200ms (user has converted; you have time)
  • Failure mode: fail open + log for offline review
  • Use cases: affiliate payouts, lead-gen, e-commerce conversion gating

Pattern 3: Post-conversion (enrichment + refund evidence)

After the conversion is counted, an async job calls the fraud API to enrich the click record with detailed signals. This data is used for refund disputes with Google Ads and Meta Ads, for retraining your own attribution model, and for offline analysis.

  • Latency budget: minutes (batch is fine)
  • Failure mode: retry with backoff; not user-blocking
  • Use cases: refund disputes, audit logs, ML feature pipelines

Most engineering teams only implement pattern 1 or pattern 2, then complain that fraud detection “isn’t catching everything.” The pattern that closes the loop is post-conversion enrichment, because it gives you per-click evidence for refund disputes, which is where you recover budget you already spent. The full three-pattern stack is what produces consistent ROI.

What does a well-designed click fraud API look like?

A production-quality click fraud detection API follows a small set of REST design conventions that make it cheap to integrate and resilient to failures. Cloudflare’s bot management documentation outlines similar latency and reliability expectations for real-time scoring services. [5] Here’s what to look for, and what to demand if you’re evaluating vendors.

REST endpoint structure

A single POST /v1/score endpoint that accepts a JSON click context and returns a verdict. Keep the request shape flat and idempotent so client retries are safe:

{
  "click_id": "abc123",
  "ip": "203.0.113.42",
  "user_agent": "Mozilla/5.0 ...",
  "referrer": "https://google.com/search?q=...",
  "campaign_id": "camp_456",
  "fingerprint": "fp_hash_xyz",
  "timestamp": "2026-05-19T14:32:01Z"
}

The response should be similarly flat and self-describing:

{
  "click_id": "abc123",
  "verdict": "block",
  "score": 0.91,
  "confidence": "high",
  "signals": ["data_center_asn", "headless_browser", "no_referrer"],
  "asn": {
    "number": 14618,
    "type": "hosting",
    "organization": "Amazon AWS"
  },
  "latency_ms": 27
}

Latency requirements

For synchronous in-funnel scoring, target p50 under 30ms, p99 under 80ms. Anything slower starts degrading conversion rates measurably. Production click fraud APIs achieve this by holding IP intelligence, ASN classification, and fingerprint hashes in memory rather than hitting a database per request. For pre-conversion postbacks, a 200ms budget is acceptable; for post-conversion enrichment, seconds are fine.

Webhook vs polling for batch scoring

For large batches (post-conversion enrichment of millions of historical clicks), polling a GET /v1/scores?since=... is wasteful. Prefer webhook delivery: you POST a batch of click contexts, the API processes async, and the verdicts arrive at a callback URL you configured. This pattern keeps your client thin and lets the API control throughput.

Rate limiting and retry semantics

Expect HTTP 429 Too Many Requests with a Retry-After header on rate limit, and 503 Service Unavailable during partial outages. Client retry should be exponential backoff with jitter, capped at three attempts. Anything more aggressive risks amplifying an upstream outage. Production APIs return X-RateLimit-Remaining and X-RateLimit-Reset headers so clients can throttle proactively.

A working integration example (Node.js + curl)

Here’s a production-ready integration. The pattern handles timeouts, fails open, logs verdicts, and keeps the scoring call off the user’s critical path where possible.

curl one-liner

For quick testing, a single curl command sends a click context and prints the verdict:

curl -X POST https://api.adsafee.com/v1/score \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"click_id":"abc123","ip":"203.0.113.42","user_agent":"Mozilla/5.0","referrer":"https://google.com/"}'

Expected response (under 100ms in production):

{
  "click_id": "abc123",
  "verdict": "allow",
  "score": 0.12,
  "signals": ["residential_asn", "valid_fingerprint"],
  "latency_ms": 24
}

Node.js production integration

The function below is what we recommend running in a Node.js backend that calls the scoring API before counting a conversion. Note the 200ms timeout, the fail-open default, and the structured logging:

const FRAUD_API_URL = 'https://api.adsafee.com/v1/score';
const FRAUD_API_KEY = process.env.ADSAFEE_API_KEY;
const TIMEOUT_MS = 200;

async function scoreClick(context) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);

  try {
    const response = await fetch(FRAUD_API_URL, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${FRAUD_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(context),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      logger.warn('fraud_api_error', { status: response.status, click_id: context.click_id });
      return { verdict: 'allow', reason: 'api_error', score: null };
    }

    const result = await response.json();
    logger.info('fraud_verdict', {
      click_id: context.click_id,
      verdict: result.verdict,
      score: result.score,
      signals: result.signals,
      latency_ms: result.latency_ms,
    });

    return result;
  } catch (err) {
    clearTimeout(timeoutId);
    logger.warn('fraud_api_timeout_or_error', { error: err.name, click_id: context.click_id });
    return { verdict: 'allow', reason: 'timeout_or_network', score: null };
  }
}

// Usage in a conversion handler
async function handleConversion(req, res) {
  const result = await scoreClick({
    click_id: req.body.click_id,
    ip: req.ip,
    user_agent: req.headers['user-agent'],
    referrer: req.headers['referer'] || null,
    campaign_id: req.body.campaign_id,
    timestamp: new Date().toISOString(),
  });

  if (result.verdict === 'block') {
    return res.status(200).json({ counted: false, reason: 'invalid_traffic' });
  }

  await countConversion(req.body);
  return res.status(200).json({ counted: true });
}

We’ve seen teams ship the scoring call without a timeout and then page their on-call at 2am when the fraud vendor had a regional latency spike, because every conversion was hanging for 30 seconds. The 200ms timeout + fail-open pattern is non-negotiable in production. Log every timeout, but never let it block the conversion.

S2S postback integration

For affiliate trackers that fire S2S postbacks on conversion, wrap the scoring call in the same pattern, but call it before forwarding the postback:

async function forwardPostback(clickContext, payoutUrl) {
  const verdict = await scoreClick(clickContext);

  if (verdict.verdict === 'block') {
    logger.info('postback_suppressed', { click_id: clickContext.click_id, score: verdict.score });
    return { forwarded: false };
  }

  // Async forward; don't block the response on the upstream
  fetch(payoutUrl, { method: 'POST' }).catch(err => logger.error('postback_forward_failed', err));
  return { forwarded: true };
}

IP intelligence + ASN scoring under the hood

When you call a click fraud detection API, the IP intelligence solutions for ad click fraud prevention running underneath are what resolve most network-layer signals. Industry research from HUMAN Security and IAS shows standard rule-based filtering catches under 40% of sophisticated bots without multi-layer network intelligence. [2]

ASN classification

Every IP belongs to an Autonomous System (ASN). The API resolves the ASN and classifies it into broad categories:

  • Data center (AWS, Google Cloud, DigitalOcean) — almost never a real user
  • Hosting (smaller cloud providers, dedicated server companies) — usually bot
  • Residential (Comcast, Deutsche Telekom, Reliance Jio) — real users, but also residential proxies
  • Mobile (Verizon Wireless, Vodafone) — real users, harder to fake
  • Business (enterprise networks) — real users behind corporate egress

A click from a hosting ASN with no referrer is high-confidence fraud. A click from a residential ASN with valid fingerprint and a real referrer is high-confidence legitimate. The combination of ASN + other signals is what produces accurate scoring. For deeper coverage of the bot-traffic surface, see our bot traffic detection guide.

Residential proxy detection

The hardest IP-layer problem in 2026: residential proxy services (BrightData, Smartproxy, IPRoyal, etc.) route fraud traffic through real consumer IPs. The ASN looks residential, but the IP is being rented out as an exit node.

Detection signals:

  • Rapid IP churn — one device fingerprint behind dozens of distinct IPs in a short window
  • Geographic inconsistency — IP geolocation cycling across countries for the same session
  • Known residential proxy exit-node lists — public and vendor-private feeds
  • Reverse DNS patterns — some proxy services leak identifying PTR records

Residential proxy detection is the single highest-value IP intelligence feature for modern click fraud APIs. Without it, anyone running BrightData against your ads looks like a legitimate user.

Known abuser lists

Threat intelligence feeds layer on top of ASN classification:

  • Spamhaus — long-standing reputation database covering known bad actors
  • Project Honeypot — public honeypot network that surfaces active bot operators
  • Vendor-private blocklists — proprietary lists from each detection vendor based on observed fraud patterns

The combination of public and private threat intel is what catches “known fraud” before behavioral or fingerprint signals are even needed.

What are the common click fraud API integration pitfalls?

In production audits, the same five integration mistakes show up across most teams. Each has a specific fix.

1. Synchronous block on slow scoring

Symptom: when the fraud API is slow, your conversion handler blocks for seconds, conversions drop, and engineers panic.

Fix: set a hard AbortController timeout (200ms for in-funnel, 500ms for postback) and fail open. The cost of allowing a small percentage of fraud is always lower than the cost of blocking real conversions during a vendor outage.

2. Caching scoring per IP misses session context

Symptom: you cache verdicts by IP for an hour to reduce API costs, and you start flagging real users who happen to share an IP with someone the API previously flagged.

Fix: don’t cache verdicts. Cache IP reputation tier (clean/suspicious/blocked) for short windows. Compute the final verdict per request using current session context (UA, fingerprint, referrer). If you need to cache, cache only on full deterministic context keys.

3. S2S postback delays vs conversion attribution

Symptom: your postback to the ad network is delayed because you’re waiting on the fraud verdict, and the ad network attributes the conversion to the wrong campaign or drops it entirely.

Fix: fire the postback async. Score the click in parallel; if the verdict comes back “block” within a few seconds, send a separate “invalid” postback to override the original. Don’t make attribution wait on fraud scoring.

4. No idempotency on retries

Symptom: client retries on 5xx errors create duplicate scoring records; downstream pipelines double-count clicks.

Fix: include click_id as an idempotency key in the request. The API should deduplicate on click_id within a configurable window (typically 24 hours). Verify your retry logic respects Retry-After headers and doesn’t hammer the API during outages.

5. Ignoring 4xx errors

Symptom: your client treats all non-2xx as “error, fail open” and silently drops scoring on misconfigured requests (missing fields, bad API key, invalid IP format).

Fix: distinguish 4xx (your bug) from 5xx (vendor problem) in logs and alerting. 4xx should page someone; 5xx should fail open quietly. Log the response body for 4xx so you can debug field validation issues.

Should you build or buy a click fraud detection API?

The decision framework comes down to scale, team, and uniqueness of your fraud surface. Rough guidance from field experience:

ScaleRecommendationWhy
Under 10M clicks/yearBuyVendor cost is rounding error; build cost is at least 1 engineer-year
10M-100M clicks/yearBuyVendor pricing scales sub-linearly; build still needs 2 engineers full-time
100M-1B clicks/yearHybridBuy detection (ASN, proxy, threat intel); build orchestration and custom rules
Over 1B clicks/yearConsider buildVendor cost grows linearly; in-house ML on your data may produce edges

The cost of “buy” is the API itself plus integration time (typically 1-2 engineer-weeks). The cost of “build” is the ongoing data engineering: maintaining ASN classification, refreshing residential-proxy feeds, integrating threat intel, training behavioral models. That’s a 2-4 engineer team continuously, plus data licensing costs.

For most engineering teams, the hybrid pattern is best: buy a fraud detection API for the hard parts (IP intelligence, fingerprinting, residential proxy detection), and build the orchestration layer that maps verdicts to your specific business logic. For a broader vendor comparison, see our best click fraud protection software 2026 overview.

Where Adsafee fits

Adsafee provides a click fraud protection API with per-click scoring in under 80ms p99, a JavaScript tag for pre-click integration, S2S postback support for pre-conversion gating, and a REST API for post-conversion enrichment. The scoring engine combines ASN classification, residential-proxy detection, behavioral signals, technical fingerprinting, and threat intelligence feeds (Spamhaus, Project Honeypot, and vendor-private lists). Integration with Keitaro, Binom, Voluum, BeMob, RedTrack, and other affiliate trackers is built in, and the API ships evidence-grade reports formatted for Google Ads and Meta Ads refund disputes.

If you’re evaluating a click fraud detection API for your stack, start a free trial — first integration typically takes about 30 minutes for the curl pattern and a few hours for a production Node.js integration.


Sources

  1. Juniper Research, “Future Digital Advertising: AI, Ad Fraud & Ad Spend 2023-2028” — $84B in 2023, $172B projected by 2028. juniperresearch.com (accessed May 2026).

  2. HUMAN Security, “2025 Quarterly Threat Report” and Integral Ad Science, “Media Quality Report H1 2025” — sophisticated bots evade rule-based filtering at under 40% catch rate. humansecurity.com; integralads.com (accessed May 2026).

  3. Media Rating Council, “Invalid Traffic Detection and Filtration Guidelines Addendum” — definitions of GIVT vs SIVT and real-time scoring requirements. mediaratingcouncil.org (accessed May 2026).

  4. IAB Tech Lab, “OpenRTB Specification” — open-source spec and click event model. Visit: github.com/InteractiveAdvertisingBureau/openrtb.

  5. Cloudflare, “Bot Management” documentation — latency and reliability expectations for real-time bot scoring. Visit: developers.cloudflare.com/bots/.

  6. Spamhaus Project, threat intelligence feeds; Project Honeypot public honeypot network — public abuser lists referenced by IP intelligence layers. Visit: spamhaus.org and projecthoneypot.org.

Frequently asked questions

What is a click fraud protection API?

A click fraud protection API is a REST endpoint that accepts click context (IP, user agent, click ID, referrer, fingerprint) and returns a fraud verdict in under 100ms. Engineering teams call it from their landing page, tracker, or conversion postback to decide whether to count a click as valid. Unlike a SaaS dashboard, an API lets you wire scoring into custom funnels, multi-tenant systems, and bespoke attribution models without using a vendor's UI.

When should I use an API instead of a SaaS dashboard?

Use an API when you have a custom funnel that doesn't fit a vendor's UI, a multi-tenant product where each tenant needs different rules, an affiliate network that needs per-publisher scoring, or a custom attribution model. Dashboards work for standard Google Ads and Meta Ads setups. APIs are necessary when you control the click handler yourself and need verdicts to drive your own routing, logging, or postback logic.

What are the three integration patterns for a click fraud detection API?

The three patterns are pre-click (JS tag fires a synchronous scoring call on landing page load), pre-conversion (server-to-server postback sends click context before counting a conversion), and post-conversion (enrichment after the conversion fires, used for refund disputes and offline retraining). Most production stacks combine all three: pre-click for routing, pre-conversion to block payouts, post-conversion to recover budget through ad-network dispute processes.

What latency should a real-time click scoring API target?

Target p50 under 30ms and p99 under 80ms for synchronous in-funnel scoring. Anything slower starts degrading conversion rates because users see page-load delay. Production click fraud APIs run scoring in-memory against pre-loaded IP intelligence and fingerprint hashes, then return a verdict + signals JSON. For pre-conversion postbacks, a 200ms budget is acceptable since the user is no longer waiting. Always implement client-side timeouts with a fail-open default.

Should I cache click scoring per IP to reduce API calls?

No, not aggressively. IP-only caching misses session context (user agent, fingerprint, referrer, time of day) that frequently flips the verdict. A click from IP 203.0.113.42 with a clean fingerprint and a real referrer is different from the same IP with a headless-browser fingerprint and no referrer. Cache only verdicts for short windows (60-120 seconds) on identical full click context, or cache IP reputation tier (not final verdict) for longer periods.

What is IP intelligence in a click fraud context?

IP intelligence is the data layer that classifies an IP's ASN (data center, residential, mobile, hosting), reputation (Spamhaus, Project Honeypot, vendor-private blocklists), and behavior (residential proxy exit nodes, VPN, Tor, recent abuse signals). For click fraud prevention, it's one of three signal layers alongside behavioral analysis and technical fingerprinting. ASN classification alone catches roughly 30-40% of automated bot traffic; combined with residential-proxy detection it covers most sophisticated network-layer fraud.

How do I handle API failures without blocking conversions?

Fail open. Set a hard client-side timeout (200ms for in-funnel, 500ms for postback), and if the call exceeds the budget or returns 5xx, default to allowing the click. Log the timeout for offline review. Blocking real conversions because a fraud API was slow costs more than the fraud the API would have caught. Implement a circuit breaker that trips after consecutive failures and routes around the scoring service until it recovers.

Build vs buy: when does it make sense to build your own click fraud API?

Build only if you have a dedicated security/data team, more than 1B clicks per year, and unique fraud patterns no vendor covers. Building means maintaining ASN data, residential-proxy detection, threat intel feeds, and behavioral models, which costs roughly 2-4 engineers full-time. For under 100M clicks per year, buying a click fraud detection API is consistently cheaper than building. The hybrid pattern (buy detection, build orchestration) covers most teams between those scales.