Build Your Own Google Ads Clone With Plain Python and SQLite

15 min read

The problem

You have read six parts about auctions, Ad Rank, pacing and click tracking. You can probably explain them at a whiteboard. But can you write the code that decides which ad shows, what the winner pays, and when a campaign should sit out so its budget lasts until evening?

Reading about a second price auction is one thing. Getting the price to come out as 1.21 and not 1.20 or 2.00 is another. So in this part we build a small ad server of our own, run it on our test machine, and show you what it actually printed.

The project is called mini-ads. It is open source under the MIT license at github.com/NafiGit/mini-ads. It uses only the Python 3 standard library: http.server, sqlite3, json, hmac, hashlib and unittest. No pip install. The engine is under 800 lines of Python, plus a small JavaScript tag.

One warning up front, and the README says the same thing: this is a teaching model. Google lists the factors that go into Ad Rank but does not publish a formula. The maths in mini-ads is a common textbook version that has the right shape, not Google's real system.

What we built

mini-ads does the core jobs of a search and display ad system:

JobWhere it lives
Advertisers, campaigns and ads, with a JSON APIminiads/server.py, miniads/db.py
Ad request endpoint GET /serveminiads/server.py, miniads/engine.py
Publisher tag that fills slots and sends a view beaconstatic/tag.js
Eligibility: targeting, schedule, budget, frequency capminiads/engine.py
Predicted CTR with a Bayesian priorminiads/auction.py
Ad rank, reserve price and generalized second priceminiads/auction.py
Signed click links, one charge per impressionminiads/tokens.py, miniads/engine.py
Budget pacingminiads/pacing.py
Reports as JSON and a small dashboardminiads/engine.py, static/dashboard.html
A one day simulation and 22 unit testsscripts/simulate.py, tests/

A campaign has a daily budget, either a max CPC bid or a target CPM, start and end dates, keywords and page categories, and a frequency cap per user per day. An ad has a headline, description, display URL and landing URL.

Here is the life of one request:

sequenceDiagram
    participant Page as Publisher page (tag.js)
    participant S as mini-ads server
    participant DB as SQLite
    participant Ad as Advertiser site
    Page->>S: GET /serve?slot=top&page=sports&kw=running+shoes&uid=...
    S->>DB: load active campaigns, spend today, user frequency
    S->>S: eligibility, pacing, auction, GSP prices
    S->>DB: log impressions with the price
    S->>Page: ads JSON with signed click and view links
    Page->>S: POST /view?token=... (50% visible for 1s)
    Page->>S: GET /click?token=... (reader clicks)
    S->>DB: check signature, charge once
    S->>Ad: 302 redirect to landing URL

Step one: who gets into the auction

Before any maths, most ads are thrown out. For every active ad, eligible_candidates in engine.py checks, in order:

flowchart LR
    A[Every active ad] ==> B{Keyword or category match?}
    B ==>|yes| C{Inside start and end date?}
    C ==>|yes| D{At least one max charge of budget left?}
    D ==>|yes| E{User under frequency cap?}
    E ==>|yes| F{Pacing lets it in?}
    F ==>|yes| G[Ad rotation picks one ad per campaign]
    G ==> H[Auction]

Each rejection is recorded with a reason, so /serve?debug=1 can tell you why an ad did not show. That one feature saves a lot of guessing.

The budget rule is deliberately cautious: a CPC campaign needs at least its max CPC left before it may enter. Then at click time, the charge is capped at whatever budget is left. Together, those two checks mean a campaign in mini-ads never spends past its daily budget. Real Google Ads works differently, as we will see at the end.

Step two: predicting the click

A CPC bid is a price per click. To compare it with other ads, you need to know how likely a click is. mini-ads learns a predicted CTR for each ad from its own history:

python
def predicted_ctr(impressions, clicks, a=PRIOR_CLICKS, b=PRIOR_NON_CLICKS):
    """Smoothed CTR: (clicks + a) / (impressions + a + b).

    With no data this is a / (a + b). As impressions grow, the prior fades
    and the estimate moves toward the real clicks / impressions.
    """
    return (clicks + a) / (impressions + a + b)

With a = 1 and b = 99, a brand new ad is treated as if it had 1 click in 100 views, so 1%. That matters. Without a prior, an ad with 1 click from 2 views would claim a 50% CTR and win everything. With the prior, it reads (1 + 1) / (2 + 100), about 2%, and has to earn the rest.

There is a trap here, and we hit it while building. If each campaign always shows its ad with the best predicted CTR, a second ad never gets impressions, so its estimate never moves, so it never wins. The fix is ad rotation: 90% of the time pick the best ad, 10% of the time a random one. That is the explore and exploit trade in one line of code.

Step three: rank and price

Relevance is a simple score from 0 to 1: 1.0 when the search equals a campaign keyword, 0.5 to 1.0 for partial word overlap, 0.75 when only the page category matches. Then:

  • For a CPC ad, rank = max CPC x predicted CTR x relevance. That is the expected money from one impression, weighted by relevance.
  • For a CPM ad, rank = target CPM / 1000 x relevance. Same unit, so CPC and CPM ads can compete in one auction.

The price follows the generalized second price rule (GSP), the auction studied by Edelman, Ostrovsky and Schwarz. Google's help page on actual CPC describes the same idea in words: you pay what is minimally required to clear the thresholds and beat the Ad Rank of the competitor just below you, rounded up to the nearest billable unit, which in the US is $0.01. In mini-ads:

price = next rank / (your predicted CTR x your relevance) + 0.01, never more than your bid

Here is the real code from auction.py, after the ads have been scored:

python
    ranked = sorted(best.values(), key=lambda c: (-c["rank"], c["ad_id"]))

    winners = []
    for i, c in enumerate(ranked[:slots]):
        if i + 1 < len(ranked):
            next_rank = max(ranked[i + 1]["rank"], reserve_rank)
        else:
            next_rank = reserve_rank
        raw = next_rank / quality(c)
        price = min(own_bid(c), round(raw + MIN_INCREMENT, 2))
        c["price"] = price
        c["position"] = i + 1
        winners.append(c)
    return winners

The reserve (a floor price) is 0.10 eCPM of rank. Ads below it never win, and the last winner on the page prices against it instead of against nobody.

A worked example

Search running shoes, two ad slots, three eligible CPC ads:

AdMax CPCPredicted CTRRelevanceRank per impression
A2.005%1.002.00 x 0.05 x 1.00 = 0.100
B3.002%1.003.00 x 0.02 x 1.00 = 0.060
C1.504%0.751.50 x 0.04 x 0.75 = 0.045

A wins slot 1 even though B bid more, because A is far more likely to be clicked. A pays 0.060 / (0.05 x 1.00) + 0.01 = 1.21 per click, well under its 2.00 bid. B takes slot 2 and pays 0.045 / (0.02 x 1.00) + 0.01 = 2.26. C shows nowhere.

Notice the odd result: B pays more per click than A, from a lower position. That is not a bug. B's ad is less clickable, so it needs a higher price per click to produce the same rank. This example is a unit test in the repo (test_worked_example_two_slots), and it passes.

There is also a randomized test that runs 500 random auctions and checks the key GSP promise: if a winner pays its price instead of its bid, its rank still beats the ad below it.

Step four: clicks you can trust

The click link carries the impression id. If anyone could edit it, they could bill a rival for clicks that never happened. So the payload is signed with HMAC SHA256:

python
def sign(payload, key=None):
    body = _b64(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
    sig = hmac.new(key or secret(), body.encode(), hashlib.sha256).digest()
    return body + "." + _b64(sig)

The key comes from the MINIADS_SECRET environment variable. The fallback in the code is named dev-only-insecure-secret-change-me, so nobody mistakes it for a real secret.

The payload also has an expiry, one hour after the ad was served. Then the click handler adds the most basic invalid traffic rule there is: one charge per impression.

python
    dup = conn.execute("SELECT 1 FROM clicks WHERE impression_id=?", (imp["id"],)).fetchone()
    if dup:
        conn.execute("INSERT INTO invalid_clicks (impression_id, reason, ts) VALUES (?,'duplicate',?)", (imp["id"], now))
        conn.commit()
        return 302, landing, "duplicate, not charged"
    cost = 0.0
    if imp["bid_type"] == "cpc":
        # Charge the second price set at auction time, never past the budget.
        day = db.day_of(now)
        left = imp["daily_budget"] - db.spend_today(conn, imp["campaign_id"], day)
        cost = max(0.0, min(imp["price"], left))

A duplicate still gets redirected. The reader did nothing wrong by double clicking, so they still land on the page. The advertiser just is not billed twice.

Step five: was the ad even seen?

An ad server logs an impression when it sends an ad, not when anyone sees it. The MRC and IAB viewable impression guidelines set the bar for display ads: at least 50% of the ad's pixels in view, for at least one continuous second. static/tag.js measures that with IntersectionObserver:

javascript
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (e) {
        if (sent) return;
        if (e.intersectionRatio >= 0.5) {
          if (!timer) {
            timer = setTimeout(function () {
              sent = true;
              beacon(url);
              io.disconnect();
            }, 1000);
          }
        } else if (timer) {
          clearTimeout(timer);
          timer = null;
        }
      });
    }, { threshold: [0, 0.5, 1] });

If the ad drops below half visible before the second is up, the timer resets. That is the "continuous" part. The real guidelines also require an in focus browser tab, which this tag does not check, so call it viewability-ish.

A publisher uses it like this (this is static/demo.html):

html
<div data-miniads-slot="top" data-page="sports" data-kw="running shoes" data-n="2"></div>
<script src="/static/tag.js" async></script>

To be plain about what we tested: the server served demo.html and tag.js (HTTP 200), and tag.js passed a JavaScript syntax check. We could not run a headless browser on our test machine, so the tag's rendering and the beacon timing were not run in a real browser for this article. The /view endpoint itself was tested with curl, below.

Step six: pacing

Without pacing, a campaign with plenty of matching traffic spends its whole budget in the first hours and vanishes for the rest of the day. mini-ads uses probabilistic throttling:

python
    if budget <= 0:
        return 0.0
    target = budget * min(1.0, elapsed + slack)
    if spent <= target:
        return 1.0
    return (target / spent) ** steepness

elapsed is the share of the UTC day that has passed, slack is 0.02 and steepness is 4. On schedule or behind, the campaign enters every auction. Ahead of schedule, it enters with a probability that falls fast the further ahead it gets. At 06:00 with 50% of the budget gone, the target is 27%, so the campaign enters about (27 / 50) to the fourth power, about 8.5% of auctions.

Running it for real

Everything below was run on our test machine on December 5, 2026, with Python 3.12.3. First the seed and server:

text
$ python3 scripts/seed.py
seeded 4 advertisers, 4 campaigns, 5 ads into miniads.db
$ MINIADS_PORT=8765 MINIADS_QUIET=1 python3 -m miniads.server
mini-ads listening on http://127.0.0.1:8765 (db: miniads.db)

The demo advertisers are made up: Stride Shoes, PeakGear, FitFuel (a CPM campaign) and CityBikes. Then we ran sh scripts/demo_curl.sh http://127.0.0.1:8765, which is in the repo. The script shortens the long tokens to ... when printing. Here is the first request, two slots with debug info:

text
== 1. ask for two ads, with auction debug info
{
  "slot": "top",
  "ads": [
    {
      "position": 1,
      "headline": "PeakGear Running Shoes",
      "description": "Lightweight, tested on real trails.",
      "display_url": "peakgear.example",
      "click_url": "/click?token=...",
      "view_url": "/view?token=...",
      "debug": {
        "ad_id": 3,
        "bid_type": "cpc",
        "bid": 2.0,
        "pctr": 0.01,
        "relevance": 1.0,
        "ecpm_rank": 20.0,
        "price": 1.21
      }
    },
    {
      "position": 2,
      "headline": "Trail Shoes That Grip",
      "description": "Free returns on every pair.",
      "display_url": "stride.example/trail",
      "click_url": "/click?token=...",
      "view_url": "/view?token=...",
      "debug": {
        "ad_id": 1,
        "bid_type": "cpc",
        "bid": 1.2,
        "pctr": 0.01,
        "relevance": 1.0,
        "ecpm_rank": 12.0,
        "price": 0.31
      }
    }
  ],
  "debug": {
    "candidates": [
      {
        "ad_id": 3,
        "campaign_id": 2,
        "ecpm_rank": 20.0
      },
      {
        "ad_id": 1,
        "campaign_id": 1,
        "ecpm_rank": 12.0
      },
      {
        "ad_id": 4,
        "campaign_id": 3,
        "ecpm_rank": 3.0
      }
    ],
    "skipped": [
      {
        "ad_id": 5,
        "campaign_id": 4,
        "skipped": "no keyword or category match"
      }
    ]
  }
}

Check the maths by hand. Every ad is new, so every predicted CTR is the 1% prior. PeakGear's rank is 2.00 x 0.01 x 1.0 = 0.020 per impression, shown as 20.0 eCPM. Stride's is 1.20 x 0.01 = 0.012, or 12.0. FitFuel bids a 4.00 CPM but only matches on the sports category, so 4.00 x 0.75 = 3.0. PeakGear pays 0.012 / 0.01 + 0.01 = 1.21. Stride pays 0.003 / 0.01 + 0.01 = 0.31. The bike ad was skipped because nothing about running shoes matches it.

Then the click path, on a fresh one slot request:

text
== 3. viewability beacon (what tag.js sends after 50% visible for 1s)
HTTP 204

== 4. click: charged once, then 302 to the landing page
HTTP/1.0 302 Found
Server: mini-ads/0.1 Python/3.12.3
Date: Sat, 05 Dec 2026 07:12:01 GMT
Location: https://peakgear.example/shoes?src=miniads
X-MiniAds-Click: charged 1.22


== 5. same click again: still redirects, not charged
HTTP/1.0 302 Found
Server: mini-ads/0.1 Python/3.12.3
Date: Sat, 05 Dec 2026 07:12:01 GMT
Location: https://peakgear.example/shoes?src=miniads
X-MiniAds-Click: duplicate, not charged


== 6. tampered token: last two characters changed
HTTP/1.0 400 Bad Request
Server: mini-ads/0.1 Python/3.12.3
Date: Sat, 05 Dec 2026 07:12:01 GMT
Content-Type: application/json
Access-Control-Allow-Origin: *
Content-Length: 30

{
  "error": "bad signature"
}

Why 1.22 and not 1.21? PeakGear now had one impression and no clicks, so its predicted CTR dropped a hair to 1 / 101, about 0.0099. Dividing by a slightly smaller number gives 1.212, plus 0.01, rounded to 1.22. The price reacts to every impression.

The report afterwards, trimmed to the PeakGear row and the invalid click counts:

text
    {
      "campaign_id": 2,
      "campaign": "PeakGear shoes and boots",
      "advertiser": "PeakGear",
      "bid_type": "cpc",
      "daily_budget": 15.0,
      "impressions": 2,
      "viewable": 1,
      "clicks": 1,
      "ctr": 0.5,
      "spend": 1.22,
      "avg_cpc": 1.22,
      "ecpm": 610.0
    },
...
  "invalid_clicks": {
    "bad signature": 1,
    "duplicate": 1
  }

A 50% CTR and a 610 eCPM are silly numbers, and that is the point of showing them: two impressions tell you nothing. The JSON API also worked for creating and pausing a campaign. We first created a fifth campaign with a POST, then paused it (output trimmed to three fields):

text
$ curl -s -X PATCH localhost:8765/api/campaigns/5 -d '{"active": 0}'
  "id": 5,
  "name": "CityBikes running",
  "active": 0

When we were done, we stopped the server.

A simulated day

Two impressions prove nothing, so scripts/simulate.py runs 10,000 requests spread evenly over one simulated day. Each request picks a search query, a page category and one of 3,000 users from fixed weights. Every ad has a hidden true CTR that the engine never sees. After each ad is served, the script clicks it with that probability, and 5% of clicks get clicked a second time to exercise the duplicate rule. The simulation calls the same engine.serve and engine.click functions as the HTTP server, so the logic is identical; it only skips the network.

Real output with pacing on:

text
$ python3 scripts/simulate.py 10000
Simulated 10000 requests over one day, pacing ON

ad                         imps clicks  learned     true
Trail Shoes That Grip      1428     60    3.99%    5.00%
Stride Running Shoes       1620     42    2.50%    2.50%
PeakGear Running Shoes     1727     32    1.81%    2.00%
FitFuel Whey Protein       4018     36    0.90%    1.00%
Commute By Bike            2104     59    2.72%    3.00%

campaign                    budget   spend  avg CPC     eCPM   out at
Stride trail shoes           40.00   39.05     0.38    12.81    19.9h
PeakGear shoes and boots     15.00   13.15     0.41     7.61    16.6h
FitFuel protein              10.00    0.55     0.00     0.14    never
CityBikes commuter           20.00    9.68     0.16     4.60    never

invalid clicks: {'duplicate': 12}
saved sim_output/result.json

Learned CTR for each ad over 10,000 simulated requests, moving toward the dashed true CTR lines

Every ad started at the 1% prior and moved toward its true rate. The order came out right: the best ad learned the highest CTR, the worst the lowest. The values are not exact. "Trail Shoes That Grip" ended at 3.99% against a true 5%. Its raw rate was 60 / 1428, about 4.2%, and the prior pulled it down a little more. With only 60 clicks, landing that far from the truth is ordinary noise. More data, or a smaller prior, would close the gap.

Now the same traffic, same random seed, with pacing switched off:

text
$ python3 scripts/simulate.py 10000 nopacing
Simulated 10000 requests over one day, pacing OFF

ad                         imps clicks  learned     true
Trail Shoes That Grip       909     44    4.46%    5.00%
Stride Running Shoes         35      0    0.74%    2.50%
PeakGear Running Shoes     1802     37    2.00%    2.00%
FitFuel Whey Protein       4810     52    1.08%    1.00%
Commute By Bike            2060     59    2.78%    3.00%

campaign                    budget   spend  avg CPC     eCPM   out at
Stride trail shoes           40.00   39.10     0.89    41.42     3.4h
PeakGear shoes and boots     15.00   13.83     0.37     7.67     6.2h
FitFuel protein              10.00    0.66     0.00     0.14    never
CityBikes commuter           20.00    3.72     0.06     1.81    never

invalid clicks: {'duplicate': 15}
saved sim_output/result_nopacing.json

"Out at" is the first time the campaign had less than one max charge left, so it could no longer enter auctions.

Share of daily budget spent by hour for the two shoe campaigns, with and without pacing

Without pacing, Stride was out of the market at about 03:24 and PeakGear at about 06:12. Anyone searching for running shoes after breakfast saw neither. With pacing, they lasted until about 19:54 and 16:36. Three more things fell out of the comparison:

  • Stride paid much less per click with pacing: 0.38 against 0.89, for almost the same total spend. Most likely because without pacing it spent everything in the first hours, while its ads were still new and it was up against PeakGear in nearly every auction.
  • Its second ad barely got measured without pacing. "Stride Running Shoes" got 35 impressions and no clicks, so its estimate sat at 0.74% while the truth was 2.5%. A campaign that burns out early has no time to learn.
  • CityBikes spent more with pacing (9.68 against 3.72). Our reading: the search "bike" sometimes comes from a sports page, where the shoe campaigns also qualify through their sports category, so while they are alive they push CityBikes' second price up. We did not break that down further, so treat it as a likely explanation, not a measured one.

Pacing is not perfect here either. Both shoe campaigns still ran out before midnight. Two reasons: the 2% slack lets them run a little ahead all day, and the "need one max CPC left" rule stops a campaign while it still has some budget. Stride ended with 0.95 unspent, less than its 1.20 max CPC. A smarter pacer would also expect traffic to rise and fall during the day instead of assuming a flat line.

The tests

The tests cover auction pricing, the worked example, GSP across three slots, reserve prices, one ad per campaign, CPM against CPC, pacing, token tampering, expiry, duplicate clicks, frequency caps, schedules and budgets. The last lines of the real run (the grep only drops unittest's divider line):

text
$ python3 -m unittest discover -s tests -v 2>&1 | grep -v '^[-]' | tail -5
test_tamper (test_miniads.TokenTests.test_tamper) ... ok

Ran 22 tests in 0.602s

OK

Two tests failed on the first run, and both were mistakes in the tests, not the engine. The frequency cap test asked for one slot, and PeakGear outranked Stride on every request, so Stride never showed at all; we changed it to ask for two slots. The budget test expected Stride to spend more than 2.00 of a 3.00 budget, but the rule stops a campaign once less than its 1.20 max CPC is left, so 1.96 was correct behaviour. We fixed the assertion to match the rule.

What real ad systems add

mini-ads is the skeleton. Here is what the real thing has that we left out, from Google's own documentation where possible:

  • A much richer Ad Rank. Google's "About Ad Rank" page lists six factors: your bid, the quality of your ads and landing page, Ad Rank thresholds, the competitiveness of the auction, the context of the search (terms, location, device, time and more) and the expected impact of assets. It does not publish how they are weighted. mini-ads has a bid, a CTR and a relevance score.
  • Thresholds per position. Google applies minimum Ad Rank thresholds before ranking. mini-ads has one flat reserve.
  • Machine learned prediction. A real click model uses many signals and corrects for position bias. Ours averages one ad's history and ignores position: an ad in slot 2 is treated as if it were in slot 1.
  • Conversions and automated bidding. No conversion tracking, no Smart Bidding. Advertisers set fixed bids.
  • Different budget rules. Google's spending limits page says that for most campaigns you can be charged up to 2 times your average daily budget on a given day, and no more than 30.4 times it in a month. mini-ads treats the daily budget as a hard cap.
  • Real invalid traffic detection. We have signed links, expiry and one charge per impression. Real systems filter bots, click farms and suspicious patterns at a scale this toy cannot touch.
  • Everything around the auction. Ad review, consent and privacy rules, brand safety, many currencies and time zones (we only use UTC days), exchanges and OpenRTB for display, and serving at very low latency for huge traffic.
  • Security. The JSON API has no authentication. Fine on localhost for learning. Not fine anywhere else.

What the toy does show is the shape: an ad with a lower bid can win if it is more likely to be clicked, the winner pays just enough to keep its spot, and a budget needs active pacing or it is gone by breakfast.

Try it yourself

text
git clone https://github.com/NafiGit/mini-ads
cd mini-ads
python3 scripts/seed.py
python3 -m miniads.server

Then open http://127.0.0.1:8080/static/demo.html and http://127.0.0.1:8080/dashboard, and run python3 scripts/simulate.py in a second terminal. Change the prior, the pacing steepness or the bids, and watch what moves. That is the fastest way to build intuition for an auction.

What's next

We built the buyer side and the auction. In part 8 we switch to the publisher's chair: which levers actually raise ad revenue per thousand visits, and which ones quietly wreck the page.

Sources