New

Tune a Real-Time Ad Platform with Resource Pools, RETURNING and Projections

Notebook


SingleStore Notebooks

Tune a Real-Time Ad Platform with Resource Pools, RETURNING and Projections

Note

This notebook can be run on a Free Starter Cluster. To create a Free Starter Cluster navigate to + using the left nav. You can also use your existing Standard or Premium cluster with this Notebook.

The story

It's the Monday after Super Bowl night at AdVenture Inc., the New York real-time ad startup where you are still the only developer. Search never blinked during the game, and Morgan Blaze, the CMO, told the board you're a genius.

The traffic never went home, though. One database now serves ads in milliseconds, charges advertisers' budgets as impressions land, and runs campaign reports, plus an AI agent that writes its own SQL, all against the same tables.

By 8 AM there are five tickets in your queue. SingleStore's August 2026 release (engine 10.4) has a feature for each one. This notebook builds the platform on real data and measures every fix, before and after:

| Ticket | Problem | Feature | What you will measure | |---|---|---|---| | ADV-311, Finance | Charging a budget and reading the new balance takes two round trips, and the read can see another server's charge | UPDATE ... RETURNING | Round trips, and how many concurrent writers see the wrong balance | | ADV-312, Privacy | Expiring audience segments means a SELECT then a DELETE, with a gap between them | DELETE ... RETURNING | One statement that deletes and reports what it removed | | ADV-313, Sales | One advertiser's dashboard scans every row, because the table is laid out by time and subscriber | Projections | Rows scanned with and without a projection, and what it costs on writes | | ADV-314, Data Engineering | Setup scripts break on re-run once a projection exists | DROP PROJECTION IF EXISTS | A teardown that is safe to run twice | | ADV-315, Morgan | A heavy report, and now an AI agent, slows down ad serving | CPU resource pools | Ad-serving latency with reports in the default pool, then in their own pool |

Lab notes boxes record what we measured across repeated runs. Absolute times depend on your cluster, so they are given as ratios; run the cells more than once.

What's in this notebook:

  1. Load the ad platform's data.

  2. Charge budgets with UPDATE ... RETURNING.

  3. Expire audience segments with DELETE ... RETURNING.

  4. Give each advertiser's dashboard its own layout with a projection.

  5. Make projection DDL re-runnable with DROP PROJECTION IF EXISTS.

  6. Keep reports and AI agents from slowing ad serving with resource pools.

  7. Clean up.

  8. Wrap up: what each feature is and when to use it.

Sections 1-5 run on any cluster. Section 6 needs a Standard or Premium Cluster, because resource pools need privileges a Free Starter Cluster does not grant; the notebook skips it there.

Cheat sheet. The four features on one page, with the figures we measured and the gotchas to watch for: cheat sheet (PDF).

Questions?

Reach out to us through our forum.

Action Required

If you have a Free Starter Cluster deployed already, select the database from drop-down menu at the top of this notebook. It updates the connection_url to connect to that database.

Create a database for the examples below. The cell keeps an existing ad_platform instead of dropping it, because dropping the database a notebook session is using leaves that session with no database. Section 1 clears out its tables anyway.

In [1]:

1shared_tier_check = %sql show variables like 'is_shared_tier'2if not shared_tier_check or shared_tier_check[0][1] == 'OFF':3    %sql CREATE DATABASE IF NOT EXISTS ad_platform;4    %sql USE ad_platform;5
6current_database = %sql SELECT DATABASE()7DATABASE = current_database[0][0]8if not DATABASE:9    raise RuntimeError('No database selected. On a Free Starter Cluster, pick your database in the '10                       'drop-down menu at the top of this notebook, then run this cell again.')11print(f'Using database {DATABASE}')

On a Standard or Premium Cluster there is nothing to pick in the drop-down: the notebook switches to ad_platform itself. On a Free Starter Cluster it uses the database you selected.

1. Load the ad platform's data.

Nobody tests fixes on production the morning after the Super Bowl, so start with a copy of AdVenture's platform.

The data is SingleStore's public real-time digital marketing demo: 3 million ad requests and 500 thousand purchases, streamed from S3 with pipelines into five tables:

  • requests and purchases -- the raw event streams, sharded by subscriber.

  • offers -- one campaign per advertiser, with a maximum bid, a budget and spend so far.

  • notifications -- every ad shown: when, to whom, which offer, and what it cost. Dashboards and reports read this table.

  • subscriber_segments -- audience memberships such as buyer:Photobug, each with an expiry time.

The parquet files have no timestamps, and the demo's offer and segment files are no longer published, so the load derives timestamps, 356 offers (one per vendor) and 3.5 million segment memberships from the streams. It uses CRC32, not RAND(), so every run produces the same data.

In [2]:

1import json2import random3import statistics4import threading5import time6
7import singlestoredb as s28
9
10def connect():11    """Open a connection to the notebook's database.12
13    New connections start in whatever database the drop-down menu selects,14    which may be none, so select ``DATABASE`` explicitly.15
16    Returns17    -------18    Connection19        An open connection with ``DATABASE`` selected.20
21    """22    conn = s2.connect()23    with conn.cursor() as cur:24        cur.execute(f'USE {DATABASE}')25    return conn26
27
28def query(sql, args=None):29    """Run one statement on a fresh connection and return its rows.30
31    Parameters32    ----------33    sql : str34        The statement to run.35    args : tuple, optional36        Parameters for the statement.37
38    Returns39    -------40    list of tuple41        The result rows, or an empty list for statements without a result set.42
43    """44    with connect() as conn, conn.cursor() as cur:45        cur.execute(sql, args)46        return list(cur.fetchall()) if cur.description else []

The notebook is safe to run more than once. Section 4 adds a projection, which blocks DROP TABLE, so the next cell removes it first (section 5 explains).

In [3]:

1if query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'notifications'"):2    query('DROP PROJECTION IF EXISTS notifications_by_offer ON notifications')

In [4]:

1%%sql2DROP PIPELINE IF EXISTS requests_pipeline;3DROP PIPELINE IF EXISTS purchases_pipeline;4DROP TABLE IF EXISTS requests;5DROP TABLE IF EXISTS purchases;6DROP TABLE IF EXISTS offers;7DROP TABLE IF EXISTS notifications;8DROP TABLE IF EXISTS subscriber_segments;9
10CREATE TABLE requests (11    subscriber_id BIGINT NOT NULL,12    domain TEXT NOT NULL,13    ts DATETIME(6) NOT NULL,14    SORT KEY (ts),15    SHARD KEY (subscriber_id)16);17
18CREATE TABLE purchases (19    subscriber_id BIGINT NOT NULL,20    vendor TEXT NOT NULL,21    ts DATETIME(6) NOT NULL,22    SORT KEY (ts),23    SHARD KEY (subscriber_id)24);25
26CREATE TABLE offers (27    offer_id BIGINT NOT NULL,28    customer TEXT NOT NULL,29    enabled BOOLEAN NOT NULL DEFAULT TRUE,30    maximum_bid_cents BIGINT NOT NULL,31    budget_cents BIGINT NOT NULL,32    spend_cents BIGINT NOT NULL DEFAULT 0,33    PRIMARY KEY (offer_id),34    SHARD KEY (offer_id),35    SORT KEY (offer_id)36);37
38CREATE TABLE notifications (39    ts DATETIME(6) NOT NULL,40    subscriber_id BIGINT NOT NULL,41    offer_id BIGINT NOT NULL,42    cost_cents BIGINT NOT NULL,43    SORT KEY (ts),44    SHARD KEY (subscriber_id)45);46
47CREATE TABLE subscriber_segments (48    subscriber_id BIGINT NOT NULL,49    segment TEXT NOT NULL,50    expires_at DATETIME(6) NOT NULL,51    SORT KEY (expires_at),52    SHARD KEY (subscriber_id)53);

Each event gets a timestamp in the last 30 days. A pipeline's SET clause can only compute from @variables, not target columns, so both fields are read into variables first. The load takes a few minutes.

In [5]:

1%%sql2CREATE PIPELINE requests_pipeline AS3    LOAD DATA S3 'singlestore-realtime-digital-marketing/v2/1m-16p/requests.*'4    CONFIG '{\"region\": \"us-east-1\"}'5    CREDENTIALS '{}'6    INTO TABLE requests FORMAT PARQUET (@sub <- subscriberid, @domain <- domain)7    SET subscriber_id = @sub, domain = @domain,8        ts = NOW(6) - INTERVAL (CRC32(CONCAT(@sub, @domain)) % 2592000) SECOND;9
10CREATE PIPELINE purchases_pipeline AS11    LOAD DATA S3 'singlestore-realtime-digital-marketing/v2/1m-16p/purchases.*'12    CONFIG '{\"region\": \"us-east-1\"}'13    CREDENTIALS '{}'14    INTO TABLE purchases FORMAT PARQUET (@sub <- subscriberid, @vendor <- vendor)15    SET subscriber_id = @sub, vendor = @vendor,16        ts = NOW(6) - INTERVAL (CRC32(CONCAT(@sub, @vendor)) % 2592000) SECOND;17
18START PIPELINE requests_pipeline FOREGROUND;19START PIPELINE purchases_pipeline FOREGROUND;

Now derive the rest. Every ad request becomes a shown ad, charged at its offer's maximum bid. Subscribers stay in visits:<domain> for 28 days after their last visit and in buyer:<vendor> for 29 days after their last purchase, so a few percent of memberships have already lapsed; section 3 expires them.

In [6]:

1%%sql2INSERT INTO offers (offer_id, customer, maximum_bid_cents, budget_cents)3SELECT ROW_NUMBER() OVER (ORDER BY vendor), vendor,4       5 + CRC32(vendor) % 46,5       100 * (500 + CRC32(REVERSE(vendor)) % 4500)6FROM (SELECT DISTINCT vendor FROM purchases) v;7
8INSERT INTO notifications (ts, subscriber_id, offer_id, cost_cents)9SELECT r.ts, r.subscriber_id, o.offer_id, o.maximum_bid_cents10FROM (SELECT ts, subscriber_id, 1 + CRC32(CONCAT(subscriber_id, domain)) % 356 AS offer_id FROM requests) r11JOIN offers o ON o.offer_id = r.offer_id;12
13INSERT INTO subscriber_segments (subscriber_id, segment, expires_at)14SELECT subscriber_id, CONCAT('visits:', domain), MAX(ts) + INTERVAL 28 DAY FROM requests GROUP BY 1, 215UNION ALL16SELECT subscriber_id, CONCAT('buyer:', vendor), MAX(ts) + INTERVAL 29 DAY FROM purchases GROUP BY 1, 2;17
18UPDATE offers o19JOIN (SELECT offer_id, SUM(cost_cents) AS s FROM notifications GROUP BY 1) n ON o.offer_id = n.offer_id20SET o.spend_cents = LEAST(n.s, o.budget_cents);

Loading in small batches leaves many small segments, and the background merger that combines them competes for CPU while it runs. Merge them now so the measurements below are steady:

In [7]:

1%%sql2OPTIMIZE TABLE requests FULL;3OPTIMIZE TABLE purchases FULL;4OPTIMIZE TABLE notifications FULL;5OPTIMIZE TABLE subscriber_segments FULL;

In [8]:

1%%sql2SELECT 'requests' AS table_name, COUNT(*) AS row_count FROM requests3UNION ALL SELECT 'purchases', COUNT(*) FROM purchases4UNION ALL SELECT 'offers', COUNT(*) FROM offers5UNION ALL SELECT 'notifications', COUNT(*) FROM notifications6UNION ALL SELECT 'subscriber_segments', COUNT(*) FROM subscriber_segments;

2. Charge budgets with UPDATE ... RETURNING.

ADV-311  opened 7:52 AM
Priya Raman, Finance: Three advertisers say we charged them past their budget in the fourth quarter last night. Every ad server checks the balance before it serves an impression, so how did we overspend? I owe them an answer by noon, and "the database did it" is not an answer.

Each ad shown is charged to its offer, and the ad server checks the balance before the next impression. Without RETURNING that is two statements: an UPDATE, then a SELECT for the new value. RETURNING hands back the changed rows, with their new values, in the same round trip.

In [9]:

1%%sql2UPDATE offers SET spend_cents = spend_cents + 173WHERE offer_id = 424RETURNING offer_id, customer, spend_cents, budget_cents;

Latency. One round trip instead of two. The next cell times both patterns on the same connection.

In [10]:

1def median_ms(fn, n=40):2    """Return the median wall-clock time of ``fn()`` in milliseconds.3
4    Parameters5    ----------6    fn : callable7        Function to time.8    n : int, optional9        Number of runs.10
11    Returns12    -------13    float14        Median time in milliseconds.15
16    """17    xs = []18    for _ in range(n):19        t0 = time.perf_counter()20        fn()21        xs.append((time.perf_counter() - t0) * 1000)22    return statistics.median(xs)23
24
25with connect() as conn, conn.cursor() as cur:26    def two_statements():27        cur.execute('UPDATE offers SET spend_cents = spend_cents + 1 WHERE offer_id = 42')28        cur.execute('SELECT spend_cents, budget_cents FROM offers WHERE offer_id = 42')29        cur.fetchall()30
31    def returning():32        cur.execute('UPDATE offers SET spend_cents = spend_cents + 1 WHERE offer_id = 42 '33                    'RETURNING spend_cents, budget_cents')34        cur.fetchall()35
36    print(f'UPDATE, then SELECT:  {median_ms(two_statements):5.1f} ms')37    print(f'UPDATE ... RETURNING: {median_ms(returning):5.1f} ms')

Correctness. Between your UPDATE and your SELECT, another ad server can charge the same offer, and your SELECT reports its balance. The next cell runs 8 ad servers at once, each charging offer 42 one cent 50 times and recording the balance it saw. 400 charges should mean 400 different balances.

In [11]:

1def charge_offer_42(use_returning, seen):2    """Charge offer 42 one cent, 50 times, recording the balance seen after each charge."""3    with connect() as conn, conn.cursor() as cur:4        for _ in range(50):5            if use_returning:6                cur.execute('UPDATE offers SET spend_cents = spend_cents + 1 WHERE offer_id = 42 RETURNING spend_cents')7            else:8                cur.execute('UPDATE offers SET spend_cents = spend_cents + 1 WHERE offer_id = 42')9                cur.execute('SELECT spend_cents FROM offers WHERE offer_id = 42')10            seen.append(cur.fetchone()[0])11
12
13for use_returning in (False, True):14    seen = []15    servers = [threading.Thread(target=charge_offer_42, args=(use_returning, seen)) for _ in range(8)]16    for s in servers:17        s.start()18    for s in servers:19        s.join()20    label = 'UPDATE ... RETURNING' if use_returning else 'UPDATE, then SELECT '21    print(f'{label}: {len(seen)} charges, {len(set(seen))} distinct balances seen')

Lab notes: RETURNING

With UPDATE-then-SELECT, most readings are someone else's balance: across our runs we saw between 86 and 153 distinct balances for 400 charges. With RETURNING, every ad server got its own post-charge balance, 400 of 400, in every run. The single round trip also roughly halved the time per charge.

That is Priya's overspend: each ad server checked a balance, just not its own. A budget check built on RETURNING cannot be fooled this way.

ADV-311  Resolved. Budget checks now read the balance their own charge produced, with UPDATE ... RETURNING. Priya has her noon answer.

What RETURNING does not do (yet)

These all fail on engine 10.4:

| You write | You get | |---|---| | RETURNING budget_cents - spend_cents (an expression) | syntax error 1064 -- return the columns and compute in your app | | a join, subquery or CTE in the UPDATE | 1235 "RETURNING having multiple tables" | | ORDER BY ... LIMIT with RETURNING | syntax error 1064 | | INSERT ... RETURNING | syntax error 1064 | | RETURNING inside a stored procedure | compiles, then fails at CALL with 1235 |

Column lists, RETURNING * and aliases (RETURNING spend_cents AS s) work, and inside a transaction a ROLLBACK discards the change as usual.

3. Expire audience segments with DELETE ... RETURNING.

ADV-312  opened 9:15 AM
Dana Okafor, Privacy Counsel: When a segment membership expires, we promise advertisers that the person stops being targeted. Last night the database deleted more memberships than the ad server's audit log says it was told about. I need the exact list of what was removed, every time. "Approximately" does not survive an audit.

The ad server must learn which memberships expired so it stops targeting them. The classic approach, SELECT the expired rows and then DELETE them, misses any membership that expires between the two statements: it is deleted but never reported. DELETE ... RETURNING deletes and reports in one statement, so you get back exactly what was removed.

In [12]:

1with connect() as conn, conn.cursor() as cur:2    t0 = time.perf_counter()3    cur.execute('DELETE FROM subscriber_segments WHERE expires_at <= NOW(6) RETURNING subscriber_id, segment')4    removed = cur.fetchall()5    elapsed = time.perf_counter() - t06
7print(f'Removed {len(removed):,} expired memberships in {elapsed:.2f} s. First few:')8for subscriber_id, segment in removed[:5]:9    print(f'  subscriber {subscriber_id}: {segment}')

Lab notes: the cost of DELETE ... RETURNING

Every removed row comes back to the client, so a large DELETE ... RETURNING costs more than a bare DELETE. In our runs, removing about 220 thousand rows took 3-8x as long as a bare DELETE. For batch jobs that is usually a good trade; for very large purges, return only the key columns you need.

ADV-312  Resolved. The expiry job now sends the ad server exactly the rows it deleted, from the DELETE itself. The audit log and the database agree.

4. Give each advertiser's dashboard its own layout with a projection.

ADV-313  opened 10:40 AM
Luis Ortega, Sales: Offer 42 is the biggest account we signed during the game. Their marketing team has the dashboard open all day, and every refresh takes long enough to notice. The renewal call is at 3 PM. I would love to not be apologizing on it.

notifications is laid out for the ad server: sharded by subscriber_id, sorted by ts. A dashboard asking what did offer 42 do? finds offer 42's rows on every partition, mixed in with everyone else's, so it reads the whole table.

A projection is a second copy of chosen columns, with its own shard key and sort key, kept in sync by the engine on every write. The table keeps the layout its main workload needs, and the projection serves the other one.

We measure rows scanned with PROFILE, because at 3 million rows timings are mostly network round trip, while rows scanned grow with your data.

In [13]:

1OFFER_WEEK = """2    SELECT DATE(ts) AS day, COUNT(*) AS impressions, SUM(cost_cents) AS spend_cents3    FROM notifications {hint}4    WHERE offer_id = 42 AND ts >= NOW(6) - INTERVAL 7 DAY5    GROUP BY 1 ORDER BY 1"""6
7OFFER_LATEST = """8    SELECT ts, subscriber_id, cost_cents9    FROM notifications {hint}10    WHERE offer_id = 42 ORDER BY ts DESC LIMIT 20"""11
12
13def rows_scanned(sql):14    """Run ``sql`` under PROFILE and return how many rows its table scans read.15
16    Parameters17    ----------18    sql : str19        A SELECT statement.20
21    Returns22    -------23    int24        Rows read by ColumnStoreScan operators, summed over all partitions.25
26    """27    def walk(node):28        if isinstance(node, dict):29            n = 030            if node.get('executor') == 'ColumnStoreScan' and 'actual_row_count' in node:31                v = node['actual_row_count']32                n += int(v['value'] if isinstance(v, dict) else v)33            return n + sum(walk(v) for v in node.values())34        if isinstance(node, list):35            return sum(walk(v) for v in node)36        return 037
38    with connect() as conn, conn.cursor() as cur:39        cur.execute('PROFILE ' + sql)40        cur.fetchall()41        cur.execute('SHOW PROFILE JSON')42        return walk(json.loads(cur.fetchone()[0]))43
44
45baseline = {name: rows_scanned(q.format(hint='')) for name, q in46            [('last 7 days', OFFER_WEEK), ('latest 20', OFFER_LATEST)]}47for name, n in baseline.items():48    print(f'Offer 42, {name}: {n:>9,} rows scanned')

Add a projection sharded and sorted by offer_id, holding only the four columns the dashboards read:

In [14]:

1%%sql2CREATE PROJECTION IF NOT EXISTS notifications_by_offer3    (SHARD KEY (offer_id), SORT KEY (offer_id, ts))4AS SELECT ts, offer_id, subscriber_id, cost_cents FROM notifications;

Wait for it. For a few seconds after CREATE PROJECTION returns, queries that name the projection fail with error 1877 "projection ... does not exist". Scripts that query a new projection right away should poll first:

In [15]:

1def wait_for_projection(table, projection, timeout_s=30):2    """Poll until queries can use ``projection``.3
4    Parameters5    ----------6    table : str7        The projection's base table.8    projection : str9        The projection name.10    timeout_s : float, optional11        Give up after this many seconds.12
13    """14    deadline = time.time() + timeout_s15    while True:16        try:17            query(f"SELECT 1 FROM {table} WITH (use_projection='{projection}') LIMIT 1")18            return19        except Exception:20            if time.time() > deadline:21                raise22            time.sleep(0.5)23
24
25wait_for_projection('notifications', 'notifications_by_offer')

The optimizer picks a projection by itself only for some query shapes. For a filter on its key, like offer_id = 42, name it with a hint after the table (and after its alias, if any): FROM notifications WITH (use_projection='notifications_by_offer').

In [16]:

1HINT = "WITH (use_projection='notifications_by_offer')"2for name, q in [('last 7 days', OFFER_WEEK), ('latest 20', OFFER_LATEST)]:3    n = rows_scanned(q.format(hint=HINT))4    print(f'Offer 42, {name}: {baseline[name]:>9,} rows scanned -> {n:>7,} with the projection '5          f'({baseline[name] / n:.0f}x fewer)')

ADV-313  Resolved. Offer 42's dashboard now reads a projection laid out by offer, not the whole table. Luis can take the 3 PM renewal call without apologizing.

EXPLAIN shows why: the query reads one partition (partitions:single) instead of all of them, and the scan names the projection:

In [17]:

1for line in query('EXPLAIN ' + OFFER_LATEST.format(hint=HINT)):2    print(line[0])

When the optimizer uses a projection without a hint

  • GROUP BY on the projection's shard key -- picked automatically. Check with EXPLAIN SELECT offer_id, COUNT(*) FROM notifications GROUP BY offer_id and look for PROJECTION notifications_by_offer.

  • Joins on the projection's shard key -- picked only when that beats the alternatives. A join to the 356-row offers table never used it here, because broadcasting 356 rows is cheaper.

  • Filters and key lookups -- need the hint, as above.

To rule a projection out for one query, use the hint WITH (disable_projection_replacement=1). To stop the optimizer choosing projections on its own, set consider_secondary_projection to OFF; hinted queries still use them.

What a projection costs

Every write to notifications now also writes the projection. The next cell copies 300 thousand rows into a fresh table twice, once bare and once with the same projection.

In [18]:

1def timed_copy(with_projection):2    """Insert about 300k notifications into a scratch table and return the seconds taken."""3    query('DROP TABLE IF EXISTS notifications_copy')4    query('CREATE TABLE notifications_copy LIKE notifications')5    if with_projection:6        query("""CREATE PROJECTION notifications_copy_by_offer7                 (SHARD KEY (offer_id), SORT KEY (offer_id, ts))8                 AS SELECT ts, offer_id, subscriber_id, cost_cents FROM notifications_copy""")9        wait_for_projection('notifications_copy', 'notifications_copy_by_offer')10    t0 = time.perf_counter()11    query('INSERT INTO notifications_copy SELECT * FROM notifications WHERE subscriber_id MOD 10 = 0')12    elapsed = time.perf_counter() - t013    if with_projection:14        query('DROP PROJECTION IF EXISTS notifications_copy_by_offer ON notifications_copy')15    query('DROP TABLE notifications_copy')16    return elapsed17
18
19print(f'Bulk insert, no projection:   {timed_copy(False):.2f} s')20print(f'Bulk insert, with projection: {timed_copy(True):.2f} s')

Lab notes: what a projection costs

In our runs the bulk insert ran 2-10x slower with the projection, and single-row inserts about 20% slower. The factor varies from run to run; that a projection costs something on every write does not. Measure it on your own write path before adding one to a hot table.

Projections pay off when a table is read far more than it is bulk-written, and the reads filter or group on a key the table's layout ignores. They are a Preview feature in this release.

5. Make projection DDL re-runnable with DROP PROJECTION IF EXISTS.

ADV-314  opened 1:40 PM
Sam Whitfield, Data Engineering: The staging refresh I run every afternoon just died on DROP TABLE notifications. That script has not changed in months. Did anyone touch that table today?

Someone did: you, in section 4. Try to drop the table:

In [19]:

1try:2    query('DROP TABLE notifications')3except Exception as e:4    print(e)

A table with a projection cannot be dropped until the projection is gone. That breaks the usual DROP TABLE IF EXISTS / CREATE TABLE setup script, and before this release DROP PROJECTION had no IF EXISTS, so the fix failed on a first run. The re-runnable teardown is now:

In [20]:

1%%sql2DROP PROJECTION IF EXISTS notifications_by_offer ON notifications;3DROP PROJECTION IF EXISTS notifications_by_offer ON notifications;

The second statement is a silent no-op. Three details:

  • ON <table> is required; without it the statement is a syntax error.

  • IF EXISTS covers a missing projection, not a missing table: if notifications does not exist, it fails with 1146. That is why section 1 checks information_schema.tables first.

  • CREATE PROJECTION IF NOT EXISTS is the matching half. DROP DATABASE is not blocked by projections.

ADV-314  Resolved. Sam's refresh script now starts with DROP PROJECTION IF EXISTS ... ON notifications, and runs cleanly whether or not the projection is there.

Put the projection back for the rest of the notebook:

In [21]:

1query("""CREATE PROJECTION IF NOT EXISTS notifications_by_offer2         (SHARD KEY (offer_id), SORT KEY (offer_id, ts))3         AS SELECT ts, offer_id, subscriber_id, cost_cents FROM notifications""")4wait_for_projection('notifications', 'notifications_by_offer')

6. Keep reports and AI agents from slowing ad serving with resource pools.

ADV-315  opened 3:32 PM
Morgan Blaze, Chief Marketing Officer: I demoed the platform to a new investor and the ads LAGGED. On my own phone. Theo in Analytics says it's the AI agent I connected on Friday. The agent, when asked, blamed Theo's campaign report. I don't care whose fault it is. Ads fast, report running, agent running. All three. Today.

The ad server's query is small: find the highest bid among the offers a subscriber is targeted by. But reports and the agent run on the same cluster, and a heavy join competes with it for the same CPUs.

A resource pool is a named set of limits: CPU share, memory, concurrency, a query timeout. Every query runs in one pool, by default default_pool, which has no limits. Since the August 2026 release, CPU limits work on clusters of every size.

Pools belong to the whole cluster, not a database. This section creates two pools and a database user, and section 7 removes them. On a Free Starter Cluster each cell prints a message and skips.

In [22]:

1on_starter = bool(shared_tier_check) and shared_tier_check[0][1] == 'ON'2if on_starter:3    print('Free Starter Cluster: resource pools are not available, skipping section 6.')4
5SERVE = """6    SELECT o.offer_id, o.maximum_bid_cents7    FROM subscriber_segments s JOIN offers o ON CONCAT('buyer:', o.customer) = s.segment8    WHERE s.subscriber_id = %s AND s.expires_at > NOW(6) AND o.enabled9    ORDER BY o.maximum_bid_cents DESC LIMIT 1"""10
11REPORTS = [12    """SELECT p.vendor, COUNT(DISTINCT r.domain) AS domains, COUNT(*) AS pairs13       FROM requests r JOIN purchases p ON p.subscriber_id = r.subscriber_id14       GROUP BY p.vendor ORDER BY pairs DESC LIMIT 5""",15    """SELECT SUBSTRING_INDEX(domain, '.', -1) AS tld, COUNT(DISTINCT subscriber_id)16       FROM requests WHERE domain RLIKE '^[a-m].*(box|zz|oo).*' GROUP BY 1""",17]18
19buyers = [r[0] for r in query("SELECT subscriber_id FROM subscriber_segments WHERE segment LIKE 'buyer:%' LIMIT 2000")]20
21# SingleStore compiles each query shape on first use. Run every query once now,22# so compilation does not land inside the first measurement.23if not on_starter:24    for sql in REPORTS:25        query(sql)26    query(SERVE, (buyers[0],))27
28
29def run_reports(pool, stop, done):30    """Run campaign reports in ``pool`` until ``stop`` is set, appending 1 to ``done`` per report."""31    with connect() as conn, conn.cursor() as cur:32        cur.execute(f'SET resource_pool = {pool}')33        i = 034        while not stop.is_set():35            cur.execute(REPORTS[i % len(REPORTS)])36            cur.fetchall()37            done.append(1)38            i += 139
40
41def serve_ads(report_pool=None, seconds=30, report_threads=4):42    """Serve ads for ``seconds`` while ``report_threads`` reports run in ``report_pool``.43
44    Parameters45    ----------46    report_pool : str, optional47        Pool the reports run in. With None, no reports run.48    seconds : float, optional49        How long to serve ads.50    report_threads : int, optional51        Number of concurrent report sessions.52
53    Returns54    -------55    dict56        Serving latency percentiles in milliseconds, and the number of reports completed.57
58    """59    stop, done = threading.Event(), []60    reporters = [threading.Thread(target=run_reports, args=(report_pool, stop, done))61                 for _ in range(report_threads if report_pool else 0)]62    for r in reporters:63        r.start()64    time.sleep(3 if report_pool else 0)65    latencies = []66    with connect() as conn, conn.cursor() as cur:67        start_reports = len(done)68        end = time.time() + seconds69        while time.time() < end:70            t0 = time.perf_counter()71            cur.execute(SERVE, (random.choice(buyers),))72            cur.fetchall()73            latencies.append((time.perf_counter() - t0) * 1000)74        reports = len(done) - start_reports75    stop.set()76    for r in reporters:77        r.join()78    q = statistics.quantiles(latencies, n=100)79    return {'p50': q[49], 'p95': q[94], 'p99': q[98], 'reports': reports if report_pool else None}80
81
82def show(label, r):83    reports = '' if r['reports'] is None else f"   reports completed: {r['reports']}"84    print(f"{label:28s} p50 {r['p50']:5.1f} ms   p95 {r['p95']:5.1f} ms   p99 {r['p99']:5.1f} ms{reports}")

First the baseline: ad serving alone, then with four report sessions in default_pool beside it. Each measurement takes about 30 seconds.

In [23]:

1if not on_starter:2    results = {'Serving alone': serve_ads()}3    show('Serving alone', results['Serving alone'])4    results['Reports in default_pool'] = serve_ads('default_pool')5    show('Reports in default_pool', results['Reports in default_pool'])

Watch p95 and p99: the slowest ad requests get several times slower while reports run. That is Morgan's lag: most ads were fine, and the slow ones were very slow. Now give the reports their own pool with a soft CPU limit.

Grant yourself access. Creating a pool does not let anyone use it, not even you: until you run GRANT USAGE, SET resource_pool fails with error 1231.

In [24]:

1if not on_starter:2    query('CREATE RESOURCE POOL IF NOT EXISTS campaign_reports WITH SOFT_CPU_LIMIT_PERCENTAGE = 20')3    query('GRANT USAGE ON RESOURCE POOL campaign_reports TO CURRENT_USER')4    results['Reports in campaign_reports'] = serve_ads('campaign_reports')5    for label, r in results.items():6        show(label, r)

Lab notes. Across six runs, ad-serving latency as a multiple of serving alone:

| | p50 | p95 | |---|---|---| | Reports in default_pool | 1-5x | 4-7x | | Reports in a pool with SOFT_CPU_LIMIT_PERCENTAGE = 20 | about 1x | about 2x |

The pool cut the slow tail by more than half in every run, and the median returned to baseline. The reports did not slow down: they completed as many times in their own pool as in default_pool. The pool decides who gets the CPU when both want it; it does not throw capacity away.

Before you use pools in production:

  • SOFT limits give way when CPUs are idle; HARD limits never do. Hard limits need SET GLOBAL resource_governor_cpu_limit_mode = 'HARD', and then all pools' CPU percentages must add up to 100 or less. That setting affects every pool on the cluster, so this notebook does not change it.

  • The percentage is not a speed limit for a single query. A report running alone in a 20% pool finished as fast as in default_pool; on the smallest clusters the limit rounds up to a whole CPU per node. It applies when work competes for CPU.

  • MAX_CONCURRENCY works per aggregator. MAX_CONCURRENCY = 1 still ran two queries at once on a cluster with two aggregators. It is also an effective fence: capping reports at one query each protected serving as well as the CPU limit did.

  • Returning to default_pool needs a grant too. After SETting a session into a custom pool, SET resource_pool = default_pool fails with 1231 unless you have USAGE on default_pool. New sessions start there without one.

Fence an AI agent with its own login

That leaves Morgan's agent. An AI agent that writes its own SQL is a report you have not read yet: it might forget a join condition, or ask the same question twenty times at once. A pool can hold it to a memory share, a concurrency cap and a query timeout, and a login whose default pool is the fenced one means it cannot switch them off.

SingleStore does this for its own agent: if you have used Aura Analyst here, the list below includes an auraanalyst pool with a memory cap, a timeout and a queue limit:

In [25]:

1if not on_starter:2    print(f"{'pool':24s} {'memory %':>8s} {'timeout s':>9s} {'max conc':>8s} {'soft CPU %':>10s} {'queue':>5s}")3    for row in query("""SELECT pool_name, memory_percentage, query_timeout, max_concurrency,4                               soft_cpu_limit_percentage, max_queue_depth5                        FROM information_schema.resource_pools ORDER BY pool_name"""):6        name, *limits = row7        print(f'{name:24s} ' + ' '.join(f"{'-' if v is None else v:>{w}}" for v, w in zip(limits, [8, 9, 8, 10, 5])))

Create a pool for your agent and a login that lands in it. WITH is required before DEFAULT RESOURCE POOL, the password must meet the cluster's policy (at least 14 characters on Helios), and the login needs no USAGE grant on its own default pool.

In [26]:

1import secrets2from urllib.parse import urlparse3
4if not on_starter:5    # A random token can lack a digit or a symbol, which the cluster's password6    # policy may require, so end it with one character of each kind.7    agent_password = secrets.token_urlsafe(24) + 'Aa1!'8    query("""CREATE RESOURCE POOL IF NOT EXISTS ai_agent9             WITH MEMORY_PERCENTAGE = 20, QUERY_TIMEOUT = 5, MAX_CONCURRENCY = 2, MAX_QUEUE_DEPTH = 4""")10    query('DROP USER IF EXISTS ai_agent')11    query(f"CREATE USER ai_agent IDENTIFIED BY '{agent_password}' WITH DEFAULT RESOURCE POOL = ai_agent")12    query(f'GRANT SELECT ON {DATABASE}.* TO ai_agent')13
14    # connection_url carries the notebook's own user, which would override user= here,15    # so connect with just its host and port.16    cluster = urlparse(connection_url)17
18
19def agent_connect():20    """Connect as the ai_agent login."""21    return s2.connect(host=cluster.hostname, port=cluster.port or 3306,22                      user='ai_agent', password=agent_password, database=DATABASE)

Now act as the agent. Its session starts in the fenced pool and cannot leave, and its bad join, every request matched with every other request by the same subscriber, is stopped by the timeout instead of running for minutes:

In [27]:

1RUNAWAY = """SELECT COUNT(*) FROM requests r JOIN requests r2 ON r2.subscriber_id = r.subscriber_id2             WHERE SHA2(CONCAT(r.domain, r2.domain), 256) LIKE 'ab%'"""3
4if not on_starter:5    with agent_connect() as conn, conn.cursor() as cur:6        cur.execute('SELECT CURRENT_USER(), CURRENT_RESOURCE_POOL()')7        print('Connected as {} in pool {}'.format(*cur.fetchone()))8
9        for sql in ['SET resource_pool = default_pool', RUNAWAY]:10            t0 = time.perf_counter()11            try:12                cur.execute(sql)13                cur.fetchall()14                print(f'Succeeded: {sql.split()[0]} ...')15            except Exception as e:16                print(f'Refused after {time.perf_counter() - t0:.1f} s: {e}')

The timeout is checked periodically, so the kill (error 2293) lands a few seconds after QUERY_TIMEOUT. Killed queries are counted in information_schema.mv_resource_pool_status, the place to watch for an agent that keeps hitting its limits:

In [28]:

1if not on_starter:2    for pool, killed, finished in query("""SELECT pool_name, SUM(killed_queries), SUM(finished_queries)3                                         FROM information_schema.mv_resource_pool_status4                                         WHERE pool_name IN ('ai_agent', 'campaign_reports') GROUP BY 1"""):5        print(f'{pool:18s} killed {int(killed):3d}   finished {int(finished):4d}')

ADV-315  Resolved. Theo's reports run in campaign_reports with a soft CPU limit, and the agent logs in as ai_agent, fenced by memory, concurrency and a timeout it cannot switch off. Ads fast, report running, agent running.

Zero open tickets. Before you log off, put everything back the way you found it.

7. Clean up.

Pools and users belong to the cluster, so dropping the database leaves them behind. Remove the user, then your grant, then the pools: a pool with a USAGE grant cannot be dropped, and REVOKE fails if the grant is already gone, so each step tolerates having run before.

In [29]:

1def best_effort(sql):2    """Run ``sql``, printing instead of raising if it fails."""3    try:4        query(sql)5    except Exception as e:6        print(f'{sql} -> {e}')7
8
9if not on_starter:10    best_effort('DROP USER IF EXISTS ai_agent')11    best_effort('REVOKE USAGE ON RESOURCE POOL campaign_reports FROM CURRENT_USER')12    best_effort('DROP RESOURCE POOL IF EXISTS campaign_reports')13    best_effort('DROP RESOURCE POOL IF EXISTS ai_agent')

Drop the database; projections block DROP TABLE but not DROP DATABASE. On a Free Starter Cluster, remove the tables instead, projection first:

In [30]:

1if on_starter:2    for pipeline in ['requests_pipeline', 'purchases_pipeline']:3        query(f'DROP PIPELINE IF EXISTS {pipeline}')4    query('DROP PROJECTION IF EXISTS notifications_by_offer ON notifications')5    for table in ['requests', 'purchases', 'offers', 'notifications', 'subscriber_segments']:6        query(f'DROP TABLE IF EXISTS {table}')7else:8    query('DROP DATABASE IF EXISTS ad_platform')

8. Wrap up.

Five tickets, five features, one database:

| Feature | What it is | Use it for | Watch out for | |---|---|---|---| | UPDATE ... RETURNING | An UPDATE that returns the changed rows with their new values | Counters and balances you must read right after changing (ADV-311) | Columns only: no expressions, joins, ORDER BY ... LIMIT, or use inside procedures | | DELETE ... RETURNING | A DELETE that returns the rows it removed | Expiry and purge jobs that must report exactly what went (ADV-312) | Every row travels back to the client; return only the keys you need | | Projection | A second copy of chosen columns with its own shard and sort key, kept in sync on every write | A read path that filters or groups on a key the table's layout ignores (ADV-313) | Slower writes; filters need the use_projection hint; a few seconds before it is queryable | | DROP PROJECTION IF EXISTS ... ON t | A projection drop that is a no-op when the projection is missing | Setup and teardown scripts that run more than once (ADV-314) | A table with a projection cannot be dropped; IF EXISTS does not cover a missing table | | Resource pool | A named set of limits: CPU share, memory, concurrency, query timeout | Keeping reports from slowing latency-critical queries (ADV-315) | Needs GRANT USAGE; SOFT limits yield to idle CPU, HARD ones never do | | Login with a DEFAULT RESOURCE POOL | A database user whose sessions start in a fenced pool | AI agents and other SQL you did not write (ADV-315) | The pool's timeout fires a few seconds late; watch mv_resource_pool_status for kills |

For the syntax, error codes and gotchas on one page, keep the cheat sheet (PDF) at hand.

Details


About this Template

Measure four SingleStore 10.4 features on a real-time ad platform: UPDATE and DELETE ... RETURNING, projections, DROP PROJECTION IF EXISTS and CPU resource pools that fence reports and AI agents away from ad serving.

This Notebook can be run in Shared Tier, Standard and Enterprise deployments.

Tags

starter

See Notebook in action

Launch this notebook in SingleStore and start executing queries instantly.

License

This Notebook has been released under the Apache 2.0 open source license.