Short answer: a custom ad server stays fast by doing almost nothing on the hot path. Pick a campaign from an in-memory snapshot, sign a click URL, append one log line, and return JSON. Counting, billing and fraud analysis move to a batch job. On one 4 vCPU node this design handles roughly 3,500-7,000 ad decisions per second at p99 under 20 ms, against 150-400 per second for a database write per event. Filter bots cheaply at click time, then make the final invalid-traffic call at billing time.
The Problem & Architectural Baseline
The first version of most ad servers is a PHP script that runs SELECT * FROM campaigns on every request, then INSERTs an impression row and UPDATEs a counter. It works at 10,000 impressions a day. At a few million, three things break in order.
First, the counter row. UPDATE campaigns SET impressions = impressions + 1 takes a row lock, so every request for a popular campaign queues behind the previous one. Your whole fleet serializes on one InnoDB row and p99 latency climbs from milliseconds into seconds. Second, write amplification: each impression, viewable impression and click becomes its own disk write, and the database becomes the bottleneck long before the web tier. Third, the ad request sits on the publisher’s critical path. Slow ad calls hurt the page you are paying to appear on, so a decision budget of roughly 50 ms server-side is a sensible ceiling.
The fix is to separate the decision from the accounting. The decision must be fast and local. The accounting can be late, as long as it is exact once it lands. Every design choice below follows from that split, and each one trades something away:
| Trade-off | Naive approach | Where this blueprint lands |
|---|---|---|
| Counting accuracy vs. throughput | Exact counter updated per event | Append-only log, exact hourly totals, reports lag by up to an hour |
| Budget pacing | Global real-time cap in the database | Soft caps per node, small overspend possible |
| Bot filtering precision vs. revenue | Block at request time on any suspicion | Cheap inline scoring, serve bots normally, decide before billing |
| Deduplication vs. privacy | Store raw IPs and cookies | Daily-rotating hashed IP, signed one-time impression IDs |
| Simplicity vs. horizontal scale | Single database for all state | Node-local state first, Redis only when you add nodes |
Industry billing agreements usually accept a small discrepancy between the ad server and the publisher’s own count, so exact-per-event accounting buys you less than it appears to. What advertisers do care about is that invalid clicks are not billed and that the counts are reproducible from raw logs. Both are easier with an append-only log than with a mutable counter.
System Architecture / Request Flow
Publisher page (ad tag JS)
| 1. GET /serve.php?z=ZONE
v
+--------------+ 2. campaign snapshot (APCu, ~30 s TTL) +---------------------+
| nginx + |<-----------------------------------------| campaigns.json |
| PHP-FPM | | (cron, atomic swap) |
+------+-------+ +---------------------+
| 3. weighted pick, signed click URL, append 's' event, return JSON
v
+--------------+ 4. creative rendered and 50% visible for 1 s -> GET /i.php
| events- |<----------------------------------------------------------
| YYYYMMDDHH | 5. user clicks -> GET /c.php -> verify HMAC -> 302 -> score
| .log |<----------------------------------------------------------
+------+-------+
| 6. hourly: aggregate.php, one transaction per file
v
+--------------+ 7. reports, billing, post-hoc fraud analysis
| MySQL |-------------------------------------------------------->
| stats_hourly |
+--------------+
- Ad request. The tag calls
/serve.php. The campaign list comes from APCu shared memory, refilled from a JSON snapshot that a cron job writes with an atomic rename. No database connection is opened on this path. - Decision. Eligible campaigns are filtered by status and node-local daily cap, then one is picked with probability proportional to its CPM bid.
- Signing. The response carries a click URL and an impression beacon URL, both signed with an HMAC over impression ID, campaign ID and timestamp. The destination URL is never in the query string.
- Impression. The tag fires the beacon only after the creative has been 50% visible for one continuous second. A
servedevent is logged at decision time, animpressionevent at beacon time, so you can measure the gap between them. - Click.
/c.phpverifies the signature, sends the 302 first, and only then scores the click. The visitor never waits on fraud logic. - Accounting. An hourly job reads each completed log file one line at a time, aggregates in memory, and upserts one row per campaign per hour inside a single transaction that also marks the file as processed.
Empirical Benchmarks & Real Comparison Data
Test profile. One 4 vCPU / 8 GB NVMe VPS running nginx and PHP 8.3-FPM with 24 static workers, a 400-byte JSON response, 20 active campaigns in the snapshot, and load generated by wrk at 256 connections for 60 seconds. Variant A runs the same PHP against a MySQL host with one insert per event and a campaign query per request. Variant C is the blueprint with cross-node dedupe and caps moved to Redis.
These are representative ranges for this architecture on this class of hardware. They are not a measured result from FortiLabs infrastructure, and your creative sizes, campaign count and network will move them. Reproduce them with the command below and replace the ranges with your own numbers before you rely on them.
wrk -t4 -c256 -d60s --latency 'https://ads.example.com/serve.php?z=1'
| Metric | A: DB write per event | B: This blueprint | C: B + Redis state |
|---|---|---|---|
| /serve p50, server time (ms) | 25-60 | 1.5-4 | 3-7 |
| /serve p99 (ms) | 250-900 | 8-20 | 12-30 |
| Ad decisions per second, 4 vCPU | 150-400 | 3,500-7,000 | 2,000-4,500 |
| Sustained impressions per day per node (40% utilization) | 5-14M | 120-240M | 70-150M |
| Click redirect p99 (ms) | 40-300 | 5-15 | 8-25 |
| Database writes per second at 3,000 impressions/s | 3,000+ | Under 1 | Under 1 |
| Memory per worker (MB) | 18-25 | 12-18 (+64 shared APCu) | 14-20 (+64 shared APCu) |
| Dedupe and daily caps across nodes | Exact | Per node, approximate | Exact |
| Commodity bot clicks flagged by inline rules | 55-80% | 55-80% | 55-80% |
| Human clicks wrongly flagged | 0.3-1.5% | 0.3-1.5% | 0.3-1.5% |
| Compute cost per 1M impressions (one $40/month node) | $0.10-0.27 | $0.006-0.011 | $0.009-0.019 |
Cost assumptions. The cost row counts the web node only. It leaves out the database host for A (which usually costs more than the web node), the Redis host for C, and CDN bandwidth for creatives. At 3,500-7,000 decisions per second and 40% average utilization, one node covers about 3.6-7.2 billion impressions a month, which is where the sub-cent figure for B comes from.
Three readings matter more than the headline numbers. First, the gain comes from removing the database from the hot path, not from PHP tricks: the same code against a per-event insert lands in column A. Second, the bot-filter rows are identical across columns because the filter code is identical. The architecture changes where state lives, not what the filter sees. Third, column C is slower than B and that is the price of exact cross-node state, so adopt it only when you actually run more than one node. Video walkthroughs of load tests like this are on the RevStack YouTube channel.
Build or Buy: When a Custom Ad Server Makes Sense
| Your situation | Recommendation | Why |
|---|---|---|
| Under about 1M impressions a month, standard banner placements | Use a hosted or open-source ad server | Google Ad Manager or Revive Adserver already cover this. Your time is worth more than the hosting saving. |
| Selling direct sponsorships with first-party reporting | Build | Simple selection logic and auditable raw logs are exactly what this design provides. |
| Custom auction, pacing or targeting rules | Build | Off-the-shelf servers make these rules hard or impossible to change. |
| Mostly programmatic demand from SSPs and exchanges | Integrate, do not rebuild | Real-time bidding needs OpenRTB support, timeout handling and seller compliance, which is a much larger project. |
| Advertisers demand accredited third-party measurement | Buy or add a verification vendor | A self-built counter cannot give you independent accreditation. |
If you would rather run a publisher-side network than operate infrastructure, AdVixo covers display monetization for publishers. The rest of this article is for teams that have decided to own the stack.
Production-Ready Code Implementation
Plain PHP 8.1+ with the APCu extension. No Composer packages, no framework, one MySQL database, and one directory of log files. The files below share a small common.php, and a cron job (every minute is enough) writes campaigns.json from the campaigns table by writing a temporary file and calling rename(), so workers never read a half-written snapshot. Set AD_SIGNING_KEY to 32 or more random bytes, hex encoded.
1. Schema
CREATE TABLE campaigns (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
status ENUM('active','paused','ended') NOT NULL DEFAULT 'paused',
bid_micro INT UNSIGNED NOT NULL, -- CPM bid in micro-currency units
creative_url VARCHAR(512) NOT NULL,
dest_url VARCHAR(2048) NOT NULL,
width SMALLINT UNSIGNED NOT NULL,
height SMALLINT UNSIGNED NOT NULL,
daily_cap INT UNSIGNED NOT NULL DEFAULT 0 -- per node, 0 = unlimited
) ENGINE=InnoDB;
CREATE TABLE stats_hourly (
campaign_id INT UNSIGNED NOT NULL,
hour_ts INT UNSIGNED NOT NULL, -- unix time truncated to the hour
served BIGINT UNSIGNED NOT NULL DEFAULT 0,
impressions BIGINT UNSIGNED NOT NULL DEFAULT 0,
clicks BIGINT UNSIGNED NOT NULL DEFAULT 0,
invalid_clicks BIGINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (campaign_id, hour_ts)
) ENGINE=InnoDB;
CREATE TABLE processed_files (
name VARCHAR(64) NOT NULL PRIMARY KEY, -- makes each log file count exactly once
processed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
2. Shared helpers: signing, snapshot cache, event log
<?php
declare(strict_types=1);
const CLICK_TTL = 86400; // a click token is valid for 24 h
function cfg(): array
{
static $c = null;
return $c ??= [
'secret' => (string) getenv('AD_SIGNING_KEY'), // 32+ random bytes, hex encoded
'snapshot' => '/var/lib/adserver/campaigns.json', // written by cron, atomic swap
'log_dir' => '/var/lib/adserver/events',
'dc_cidrs' => '/var/lib/adserver/datacenter-cidrs.txt', // one CIDR per line
'base' => 'https://ads.example.com',
];
}
function sign(string $imp, int $cid, int $ts): string
{
if (cfg()['secret'] === '') { throw new RuntimeException('AD_SIGNING_KEY is not set'); }
return substr(hash_hmac('sha256', "$imp.$cid.$ts", cfg()['secret']), 0, 32);
}
function campaigns(): array
{
$hit = apcu_fetch('campaigns:v1', $ok);
if ($ok) { return $hit; }
$raw = @file_get_contents(cfg()['snapshot']);
$list = $raw === false ? [] : (json_decode($raw, true, 8) ?: []);
$byId = [];
foreach ($list as $c) {
foreach (['id', 'bid_micro', 'daily_cap', 'width', 'height'] as $k) { $c[$k] = (int) $c[$k]; }
$byId[$c['id']] = $c;
}
apcu_store('campaigns:v1', $byId, 30 + random_int(0, 10)); // jitter stops workers refilling in lockstep
return $byId;
}
function logEvent(string $type, int $cid, string $imp, array $extra = []): void
{
$line = json_encode(['t' => time(), 'e' => $type, 'c' => $cid, 'i' => $imp] + $extra, JSON_UNESCAPED_SLASHES) . "\n";
$file = cfg()['log_dir'] . '/events-' . date('YmdH') . '.log';
if (@file_put_contents($file, $line, FILE_APPEND | LOCK_EX) === false) {
apcu_inc('metric:log_write_failed'); // scrape this counter and alert on it: lost lines are lost revenue
}
}
function ipHash(string $ip): string
{
return hash('xxh3', $ip . date('Ymd') . cfg()['secret']); // salt rotates daily, raw IPs are never stored
}
3. Ad decision endpoint: serve.php
<?php
declare(strict_types=1);
require __DIR__ . '/common.php';
header('Content-Type: application/json');
header('Cache-Control: no-store');
header('Access-Control-Allow-Origin: *'); // public endpoint, no cookies, so a wildcard is safe
$zone = (int) ($_GET['z'] ?? 0);
$day = date('Ymd');
$pool = [];
foreach (campaigns() as $c) {
if ($c['status'] !== 'active' || $c['bid_micro'] <= 0) { continue; }
$served = (int) apcu_fetch("cap:{$c['id']}:$day"); // node-local counter
if ($c['daily_cap'] > 0 && $served >= $c['daily_cap']) { continue; }
$pool[] = $c;
}
if ($pool === []) { http_response_code(204); exit; }
// Weighted pick: probability proportional to CPM bid
$r = mt_rand(1, array_sum(array_column($pool, 'bid_micro')));
foreach ($pool as $c) {
$r -= $c['bid_micro'];
if ($r <= 0) { break; }
}
apcu_inc("cap:{$c['id']}:$day", 1, $ok, 90000);
$imp = bin2hex(random_bytes(8));
$ts = time();
$q = http_build_query(['i' => $imp, 'c' => $c['id'], 't' => $ts, 's' => sign($imp, $c['id'], $ts)]);
logEvent('s', $c['id'], $imp, ['z' => $zone]);
echo json_encode([
'creative' => $c['creative_url'],
'w' => $c['width'],
'h' => $c['height'],
'click' => cfg()['base'] . '/c.php?' . $q,
'beacon' => cfg()['base'] . '/i.php?' . $q,
], JSON_UNESCAPED_SLASHES);
4. Impression beacon: i.php
<?php
declare(strict_types=1);
require __DIR__ . '/common.php';
header('Content-Type: image/gif');
header('Cache-Control: no-store');
echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'); // 1x1 transparent GIF
if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } // respond first, count after
$imp = (string) ($_GET['i'] ?? '');
$cid = (int) ($_GET['c'] ?? 0);
$ts = (int) ($_GET['t'] ?? 0);
if (preg_match('/^[0-9a-f]{16}$/', $imp) === 1
&& hash_equals(sign($imp, $cid, $ts), (string) ($_GET['s'] ?? ''))
&& apcu_add('imp:' . $imp, 1, CLICK_TTL)) { // first beacon for this impression only
logEvent('i', $cid, $imp);
}
5. Click tracking, redirect and bot scoring: c.php
<?php
declare(strict_types=1);
require __DIR__ . '/common.php';
function inCidr(string $ip, string $cidr): bool
{
$parts = explode('/', $cidr, 2);
if (count($parts) !== 2) { return false; }
$a = inet_pton($ip);
$b = inet_pton($parts[0]);
if ($a === false || $b === false || strlen($a) !== strlen($b)) { return false; }
$bits = (int) $parts[1];
$bytes = intdiv($bits, 8);
$rem = $bits % 8;
if ($bytes > 0 && substr($a, 0, $bytes) !== substr($b, 0, $bytes)) { return false; }
if ($rem === 0) { return true; }
$mask = (0xFF << (8 - $rem)) & 0xFF;
return (ord($a[$bytes]) & $mask) === (ord($b[$bytes]) & $mask);
}
function dcRanges(): array
{
$hit = apcu_fetch('dc:v1', $ok);
if ($ok) { return $hit; }
$lines = @file(cfg()['dc_cidrs'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
apcu_store('dc:v1', $lines, 3600);
return $lines;
}
function botScore(string $ip, string $ua, int $age): int
{
$s = 0;
if ($ua === '') { $s += 4; }
elseif (preg_match('/bot|crawl|spider|headless|python|curl|wget|httpclient|java\//i', $ua) === 1) { $s += 5; }
if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $s += 2; }
if ($age < 1) { $s += 4; } // clicked within a second of serve
if ((int) apcu_inc('vel:' . ipHash($ip), 1, $ok, 60) > 5) { $s += 3; } // more than 5 clicks/min from one IP
foreach (dcRanges() as $cidr) {
if (inCidr($ip, $cidr)) { $s += 3; break; }
}
return $s;
}
$imp = (string) ($_GET['i'] ?? '');
$cid = (int) ($_GET['c'] ?? 0);
$ts = (int) ($_GET['t'] ?? 0);
$campaign = campaigns()[$cid] ?? null;
if ($campaign === null
|| preg_match('/^[0-9a-f]{16}$/', $imp) !== 1
|| !hash_equals(sign($imp, $cid, $ts), (string) ($_GET['s'] ?? ''))) {
http_response_code(400);
exit;
}
// The destination comes from our own snapshot, never from the query string (no open redirect)
$dest = (string) $campaign['dest_url'];
if (!in_array(parse_url($dest, PHP_URL_SCHEME), ['http', 'https'], true)) { http_response_code(400); exit; }
header('Cache-Control: no-store');
header('Location: ' . $dest, true, 302);
if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); }
// ---- everything below runs after the visitor has already been redirected ----
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET' || ($_SERVER['HTTP_SEC_PURPOSE'] ?? '') !== '') { exit; } // HEAD, prefetch, prerender
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$age = time() - $ts;
if ($age < 0 || $age > CLICK_TTL) { logEvent('x', $cid, $imp, ['sc' => 99]); exit; }
if (!apcu_add('click:' . $imp, 1, CLICK_TTL)) { exit; } // second click on the same impression: not counted
$score = botScore($ip, $ua, $age);
logEvent($score >= 5 ? 'x' : 'c', $cid, $imp, ['h' => ipHash($ip), 'sc' => $score, 'age' => $age]);
6. Hourly aggregation: aggregate.php (run from cron once an hour, shortly after the hour)
<?php
declare(strict_types=1);
$dir = '/var/lib/adserver/events';
$pdo = new PDO((string) getenv('AD_DB_DSN'), (string) getenv('AD_DB_USER'), (string) getenv('AD_DB_PASS'), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$upsert = $pdo->prepare(
'INSERT INTO stats_hourly (campaign_id, hour_ts, served, impressions, clicks, invalid_clicks)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE served = served + VALUES(served), impressions = impressions + VALUES(impressions),
clicks = clicks + VALUES(clicks), invalid_clicks = invalid_clicks + VALUES(invalid_clicks)'
);
$mark = $pdo->prepare('INSERT INTO processed_files (name) VALUES (?)');
$current = 'events-' . date('YmdH') . '.log';
$column = ['s' => 0, 'i' => 1, 'c' => 2, 'x' => 3];
foreach (glob($dir . '/events-*.log') ?: [] as $path) {
$name = basename($path);
if ($name === $current) { continue; } // still being written
$agg = [];
$fh = fopen($path, 'rb');
if ($fh === false) { continue; }
while (($line = fgets($fh)) !== false) { // one line in memory at a time
$e = json_decode($line, true);
if (!is_array($e) || !isset($e['c'], $e['t'], $e['e'], $column[$e['e']])) { continue; } // skip torn lines
$hour = intdiv((int) $e['t'], 3600) * 3600;
$col = $column[$e['e']];
$agg[(int) $e['c']][$hour][$col] = ($agg[(int) $e['c']][$hour][$col] ?? 0) + 1;
}
fclose($fh);
$pdo->beginTransaction();
try {
$mark->execute([$name]); // duplicate key means this file was already counted
foreach ($agg as $cid => $hours) {
foreach ($hours as $hour => $n) {
$upsert->execute([$cid, $hour, $n[0] ?? 0, $n[1] ?? 0, $n[2] ?? 0, $n[3] ?? 0]);
}
}
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
if ($ex->getCode() !== '23000') { throw $ex; } // 23000 = already processed, anything else is real
}
rename($path, $path . '.done');
}
7. Publisher ad tag with viewability check
<div id="ad-slot-1"></div>
<script>
(function () {
var slot = document.getElementById('ad-slot-1');
fetch('https://ads.example.com/serve.php?z=1', { mode: 'cors' })
.then(function (r) { return r.status === 200 ? r.json() : null; })
.then(function (ad) {
if (!ad) { return; }
var a = document.createElement('a');
a.href = ad.click; a.target = '_blank'; a.rel = 'sponsored noopener';
var img = new Image();
img.width = ad.w; img.height = ad.h; img.alt = 'Advertisement';
img.onload = function () {
var timer = null, fired = false;
var io = new IntersectionObserver(function (entries) {
if (entries[0].isIntersecting && !fired) {
timer = setTimeout(function () { // 50% visible for 1 continuous second
fired = true; io.disconnect(); new Image().src = ad.beacon;
}, 1000);
} else if (timer) { clearTimeout(timer); timer = null; }
}, { threshold: 0.5 });
io.observe(img);
};
img.src = ad.creative;
a.appendChild(img); slot.appendChild(a);
})
.catch(function () {});
})();
</script>
8. Runtime configuration
; ---- php-fpm pool ----
pm = static
pm.max_children = 24
pm.max_requests = 5000
clear_env = no ; lets getenv('AD_SIGNING_KEY') work
; ---- php.ini ----
opcache.enable = 1
opcache.validate_timestamps = 0 ; reload php-fpm on deploy
apc.enabled = 1
apc.shm_size = 64M
date.timezone = UTC
display_errors = 0
# ---- nginx ----
limit_req_zone $binary_remote_addr zone=ads:20m rate=30r/s;
set_real_ip_from 10.0.0.0/8; # your load balancer or CDN ranges
real_ip_header X-Forwarded-For;
location ~ ^/(serve|i|c)\.php$ {
limit_req zone=ads burst=60 nodelay;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php-fpm.sock;
}
Why the code looks the way it does:
- No database on the hot path.
campaigns()reads from APCu shared memory and refills from a file. The TTL carries random jitter so 24 workers do not all refill in the same millisecond when the cache expires. - Signed, stateless tokens. The HMAC covers impression ID, campaign ID and timestamp, and it is compared with
hash_equals()to avoid timing leaks. A click without a valid token never reaches the log, which kills injected and fabricated clicks outright. - Redirect first, think later.
fastcgi_finish_request()flushes the 302 before any scoring runs. The visitor’s latency is signature check plus a header, and a slow fraud rule can never slow a real click. - Destination from the snapshot, not the URL. Accepting a
url=parameter turns a click tracker into an open redirect that phishers love. The OWASP guidance on unvalidated redirects explains the attack, and the scheme check blocksjavascript:style targets. - Score, do not block. Suspicious clicks are still redirected, so a bot learns nothing about what tripped it. They are logged as
xevents and excluded from billing. Scores of 5 or more count as invalid in this example; tune that threshold against your own false-positive data. - One-time impression IDs.
apcu_add()succeeds only for the first beacon and the first click per impression, which handles replays and double-clicks. It is also node-local, which is the limit the edge-case section deals with. - Append-only log with
LOCK_EX. Each event is one JSON line. A failed write increments a metric instead of breaking ad delivery, because losing a log line should alert you, not take down the page. - Exactly-once aggregation. The
processed_filesinsert and the counter upserts share one transaction. If the job crashes after the commit but before the rename, the rerun hits the duplicate key, skips the file, and renames it. Nothing is counted twice. - Memory safety. The aggregator reads with
fgets()and keeps only per-campaign-per-hour counters, so a multi-gigabyte log uses a few megabytes. - Viewability in the tag. The beacon fires after 50% of the creative has been visible for one continuous second, the usual standard for display ads. Impressions the user never saw are not counted. For events that must survive page unload, navigator.sendBeacon is the right browser API.
More ad-serving and monetization write-ups are in the Ad Tech Lab archive, and the other software FortiLabs builds is listed on the products page.
Edge Cases, Bot Filtering & Security Mitigations
A three-layer bot filter
Bot filtering works best as layers that get progressively smarter and slower. Do the cheap work early and the expensive work where latency no longer matters.
| Layer | Where | What it catches | Cost |
|---|---|---|---|
| 1. Edge | nginx or CDN | Floods, trivially abusive IPs, malformed requests (limit_req) | Near zero |
| 2. Inline score | c.php, after the redirect | Headless and script user agents, missing headers, sub-second clicks, per-IP bursts, datacenter ranges | Microseconds, no latency for the visitor |
| 3. Deferred analysis | SQL over stats_hourly and the raw logs, before invoicing | Click spam from one source, self-clicking publishers, abnormal CTR by campaign or zone | Batch, as heavy as you like |
Layer 3 is the one teams skip, and it is where accuracy comes from, because it sees aggregates no single request can show. A first-pass query for abnormal click-through rates:
SELECT campaign_id, FROM_UNIXTIME(hour_ts) AS hour,
impressions, clicks,
ROUND(100 * clicks / NULLIF(impressions, 0), 2) AS ctr_pct
FROM stats_hourly
WHERE impressions >= 1000
AND clicks / NULLIF(impressions, 0) > 0.05 -- display CTR above 5% is rarely organic
ORDER BY ctr_pct DESC;
Failure modes and mitigations
Multi-node state. APCu is per server. With two nodes behind a load balancer, one impression ID can be counted once on each, and a campaign cap is enforced per node. Either route by a hash of the impression ID so one impression always lands on the same node, or move dedupe, velocity counters and caps to Redis with SET key value NX EX ttl. That is variant C in the benchmark, and the extra 1-2 ms is the cost.
Click spam and replay. Fabricated clicks fail the HMAC. Replayed clicks fail the one-time ID. Clicks within a second of serving score high. Repeated clicks from one source trip the velocity counter. Be aware that carrier-grade NAT puts thousands of real mobile users behind one IP, so the velocity rule can punish them. If your audience is mobile-heavy, key it on IP plus a user-agent hash and watch the false-positive rate.
Prefetch and prerender. Browsers and link scanners can request a click URL without a human. The code ignores HEAD requests and anything carrying Sec-Purpose, but corporate email scanners and chat apps that unfurl links will still look like clicks. The sub-second rule and the user-agent rule catch most of them.
Impression stuffing. Pixel-sized or hidden iframes inflate served counts. Counting only after the viewability check removes most of it, and a large served-to-impression gap per zone is itself a fraud signal worth alerting on.
Token lifetime and key rotation. Tokens expire after 24 hours, and expired clicks are logged as invalid. Rotate AD_SIGNING_KEY by accepting both the old and new key for one token lifetime before dropping the old one.
Privacy. The logs never contain a raw IP. They hold a hash salted per day, which lets you detect bursts within a day but not track a person across days. Rules on tracking and consent differ by region, so get legal advice before adding cookies or fingerprinting.
Operational failure. A full disk or a stuck aggregator silently turns into lost revenue. Alert on three things: the metric:log_write_failed counter, free disk space on the log volume, and the age of the oldest unprocessed log file.
Ad blockers and discrepancies. Blockers drop third-party ad requests and beacons, so the publisher’s analytics and your counts will disagree. Serve the tag from a first-party subdomain where the publisher agrees, and track the served-to-impression ratio per publisher so you can explain the gap instead of arguing about it.
Creative safety. Serve only creatives you have reviewed, hosted on your own CDN, and render third-party HTML creatives in sandboxed iframes. One malicious creative on your network damages every publisher using it.
Production Verdict
Keep the hot path boring: memory in, one signed response out, one line appended to a file. Everything that needs to be exact, such as billing and invalid-traffic decisions, happens later against raw logs where you can rerun it. On a single modest node this carries well over a hundred million impressions a day.
Move to Redis the day you add a second web node, not before. Move the log pipeline to a stream and a columnar store only when hourly batches stop being fast enough for your reporting needs. Until then, plain files and one upsert per campaign-hour are easy to audit and hard to break. If you build this, the first week of data will tell you more about your real bot traffic than any vendor claim, so start the layer-3 queries on day one. Teardowns of ad-tech systems like this one are published on the RevStack YouTube channel and in the FortiLabs blog.
Frequently Asked Questions
How many impressions can a PHP ad server handle?
With campaign data cached in memory and events appended to a log instead of written to a database, one 4 vCPU node can typically decide 3,500-7,000 ad requests per second. At 40% average utilization that is roughly 120-240 million impressions a day. A design that writes to a database on every event usually tops out at a few hundred requests per second.
How do you track ad clicks without slowing the redirect?
Verify a signed token, send the 302 redirect immediately, and do the logging and bot scoring after the response has been flushed. In PHP-FPM, fastcgi_finish_request() does this. The visitor only waits for the signature check.
How do you filter bot clicks in an ad server?
Use layers. Edge rate limits stop floods, an inline score on user agent, headers, click timing, per-IP velocity and datacenter ranges catches commodity bots, and batch analysis of click-through rates before invoicing catches coordinated fraud. Log suspicious clicks as invalid instead of blocking them.
Why count impressions with a beacon instead of at serve time?
Serving a creative does not mean anyone saw it. A beacon that fires after the ad has been 50% visible for one second approximates a viewable impression, and the gap between served and viewed events is a useful quality and fraud signal.
Should I use Redis or MySQL for impression counters?
Neither on the hot path at first. Append events to a log file and aggregate them into MySQL once an hour. Add Redis when you run multiple web nodes and need exact shared deduplication and caps.
When should I use Google Ad Manager or Revive Adserver instead of building one?
Use an existing ad server when traffic is small, your needs are standard banner placements, or your demand is mostly programmatic through exchanges. Build your own when you need custom selection logic, first-party auditable logs, or direct-sold inventory with your own reporting.