Scale Read Workloads with Smart Attach Read Replicas
Notebook
The story
It's the last week of March at AdVenture Inc., the New York real-time ad startup where you are still the only developer. In February, resource pools fenced Theo's campaign reports into 20% of the CPU, and ad serving has been fast ever since.
Then the quarter closed. Theo needs a week of reports in two days, Finance closes the books on live spend, and Morgan Blaze, the CMO, has promised advertisers an AI agent that answers questions about their own campaigns. A pool can only divide one cluster's CPUs. This quarter, the readers need machines of their own.
Smart Attach attaches one database to more than one cluster: one cluster reads and writes it, and any number of others attach it read-only. The readers copy nothing. They read the same database from shared object storage, keep their own cache, and replay the writer's changes as they happen.
By 8 AM there are five tickets in your queue:
| Ticket | Problem | What you will do and measure | |---|---|---| | ADV-341, Analytics | Quarter-end reports need more CPU than a pool can spare from ad serving | Create a reader cluster, attach the database read-only, and measure ad-serving latency with reports on the writer, then on the reader | | ADV-342, Morgan | The AI agent must be unable to change anything | Try every kind of write on the reader | | ADV-343, Finance | How old are the numbers the reader returns? | Time how long a budget charge on the writer takes to appear on the reader, with the writer idle and busy | | ADV-344, Data Engineering | The reader should be sized on its own, and schema changes should reach it | Add a column on the writer and watch it arrive; compare the two clusters' sizes | | ADV-345, Morgan | Turn the reader off after the close, without touching ad serving | Detach the database from the reader while the writer keeps writing |
Lab notes boxes record what we measured across repeated runs.
What's in this notebook:
Load the ad platform's data on this cluster, the writer.
Give the reports a reader of their own.
Measure ad serving with reports on the writer, then on the reader.
Make sure the AI agent cannot write.
Measure how fresh the reader is.
Watch a schema change reach the reader, and size the reader on its own.
Detach the reader while ads keep serving.
Clean up.
Wrap up: what Smart Attach is and when to use it.
Before you start
Run this notebook on an Enterprise edition cluster. Read-only attachments need a second cluster, which a Free Starter Cluster cannot have.
The notebook needs a second cluster in the same region to be the reader. Section 2 creates the smallest size, in this cluster's project, and section 7 terminates it; it is billed while it runs, usually under half an hour. If your account cannot create another cluster, set
READER_CLUSTERin section 2 to the name of one you already have in this region, and the notebook will attach to it, read from it and detach again, without resizing or terminating it.
Questions?
Reach out to us through our forum.
Creating a cluster from a notebook needs version 1.18 or later of the singlestoredb client. Install it, then restart the kernel (Kernel > Restart) before you run the next cell.
In [1]:
1%pip install -q "singlestoredb>=1.18"
In [2]:
1import singlestoredb as s22 3if not hasattr(s2, 'manage_workspaces'):4 raise RuntimeError(f'singlestoredb {s2.__version__} is loaded. Restart the kernel (Kernel > Restart), '5 'then run this cell again.')6print(f'singlestoredb {s2.__version__}')
Action Required
Leave the database drop-down at the top of this notebook as it is. The next cell creates ad_platform on this cluster and switches to it.
Create the database. 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 [3]:
1shared_tier_check = %sql show variables like 'is_shared_tier'2if shared_tier_check and shared_tier_check[0][1] == 'ON':3 raise RuntimeError('This is a Free Starter Cluster. Read-only attachments need an Enterprise '4 'edition cluster, so this notebook cannot run here.')5 6%sql CREATE DATABASE IF NOT EXISTS ad_platform;7%sql USE ad_platform;8DATABASE = 'ad_platform'9print(f'Using database {DATABASE}')
1. Load the ad platform's data on this cluster, the writer.
Start with a fresh copy of AdVenture's platform, the same data as the previous notebook in this series, Tune a Real-Time Ad Platform. This cluster is the writer: ad serving and budget charges stay here.
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:
requestsandpurchases-- 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. Reports read this table.subscriber_segments-- audience memberships such asbuyer:Photobug, each with an expiry time.
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 [4]:
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. If you ran the previous notebook and kept its data, its projection on notifications blocks DROP TABLE, so the next cell removes it first.
In [5]:
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 [6]:
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 [7]:
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.
In [8]:
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 [9]:
1%%sql2OPTIMIZE TABLE requests FULL;3OPTIMIZE TABLE purchases FULL;4OPTIMIZE TABLE notifications FULL;5OPTIMIZE TABLE subscriber_segments FULL;
In [10]:
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. Give the reports a reader of their own.
Theo Park, Analytics: Close starts today. The campaign_reports pool kept ads fast in February, but at 20% of the CPU my close reports will take all week. Can I have a machine of my own? And no copies: the last time someone exported a CSV, Finance closed the quarter on stale numbers.
A pool divides one cluster's CPUs; it cannot add more. A reader is a second cluster with its own CPUs, memory and cache, attached to the same database read-only. Nothing is copied: the database stays in shared object storage, the reader caches what its queries touch, and it replays the writer's changes as they are committed.
The reader must be in the same region as the writer. The next cell creates the smallest cluster in this cluster's region and project, with this cluster's firewall rules, and waits until it is running, which takes a few minutes. It expires after 4 hours in case the notebook stops before section 7 terminates it.
To use a cluster you already have instead, set READER_CLUSTER to its name. The notebook never resizes or terminates a cluster it did not create.
In [11]:
1import os2from urllib.parse import unquote, urlparse3 4# None creates a new reader. To use an existing cluster in the same region, set its name here.5READER_CLUSTER = None6READER_SIZE = 'S-00'7 8clusters = s2.manage_workspaces()9writer = clusters.get_workspace(os.environ['SINGLESTOREDB_WORKSPACE'])10print(f'Writer: {writer.name}, size {writer.size}, {writer.provider} {writer.region.region_name}')
In [12]:
1def find_cluster(name):2 """Return the running cluster called ``name`` in this organization, or None."""3 matches = [c for c in clusters.clusters if c.name == name and c.state != 'TERMINATED']4 return matches[0] if matches else None5 6 7created_reader = False8if READER_CLUSTER:9 reader = find_cluster(READER_CLUSTER)10 if reader is None:11 raise RuntimeError(f'No cluster named {READER_CLUSTER!r} was found.')12else:13 # A rerun finds the reader an earlier run created, instead of making a second one.14 name = f'{writer.name}-reports'15 reader = find_cluster(name)16 if reader is None:17 try:18 reader = clusters.create_workspace(19 name=name, region=writer.region, size=READER_SIZE, project=writer.project,20 firewall_ranges=list(writer.firewall_ranges), allow_all_traffic=writer.allow_all_traffic,21 expires_at='4h', wait_on_active=True, wait_timeout=1800)22 except s2.ManagementError as e:23 if 'maximum number' in str(e):24 raise RuntimeError('Your account cannot create another cluster. Set READER_CLUSTER '25 'to the name of an existing cluster in the same region, and run '26 'this cell again.') from e27 raise28 created_reader = True29 30if reader.id == writer.id:31 raise RuntimeError('The reader must be a different cluster from the one running this notebook.')32if (reader.provider, reader.region.region_name) != (writer.provider, writer.region.region_name):33 raise RuntimeError(f'{reader.name} is in {reader.provider} {reader.region.region_name}; '34 'a reader must be in the same region as the writer.')35if reader.state != 'ACTIVE':36 raise RuntimeError(f'{reader.name} is {reader.state}. Resume it in the portal, then run this cell again.')37 38print(f'Reader: {reader.name}, size {reader.size}' + (' (created by this notebook)' if created_reader else ''))
Connect to the reader as yourself. The users you manage in the portal exist on every cluster in your organization, so the notebook connects to the reader with its own login and needs no password. That login is a token which expires after about an hour, so reader_connect() reads the current one from the environment every time.
In [13]:
1def reader_attachment(cur):2 """Return how ``DATABASE`` exists on the reader: 'READONLY', 'WRITABLE', or None.3 4 Only a ``READONLY`` row for the reader's own cluster counts as a read-only5 attachment. Any other database of the same name on the reader, such as one6 created there, is treated as writable, so the notebook never writes to it.7 """8 cur.execute('SELECT 1 FROM information_schema.schemata WHERE schema_name = %s', (DATABASE,))9 if not cur.fetchall():10 return None11 cur.execute("""SELECT attach_type FROM information_schema.mv_cloud_attached_databases12 WHERE database_name = %s AND site_name = %s""", (DATABASE, reader.name))13 return 'READONLY' if [r[0] for r in cur.fetchall()] == ['READONLY'] else 'WRITABLE'14 15 16def require_read_only(cur):17 """Raise unless ``DATABASE`` is attached read-only to the reader."""18 if reader_attachment(cur) != 'READONLY':19 raise RuntimeError(f'{reader.name} has a database named {DATABASE} that is not a read-only '20 'attachment, so this notebook will not read or change it. Set READER_CLUSTER '21 'to a cluster without one.')22 23 24def reader_connect(database=True):25 """Open a connection to the reader as the notebook's own user.26 27 Parameters28 ----------29 database : bool, optional30 Select ``DATABASE`` on the new connection, after checking that it is31 a read-only attachment.32 33 Returns34 -------35 Connection36 An open connection to the reader.37 38 """39 login = urlparse('singlestoredb://' + os.environ['SINGLESTOREDB_URL'].split('://')[-1])40 conn = s2.connect(host=reader.endpoint, port=3306, user=unquote(login.username),41 password=unquote(login.password))42 if database:43 try:44 with conn.cursor() as cur:45 require_read_only(cur)46 cur.execute(f'USE {DATABASE}')47 except Exception:48 conn.close()49 raise50 return conn51 52 53def reader_query(sql, args=None):54 """Run one statement on the reader and return its rows."""55 with reader_connect() as conn, conn.cursor() as cur:56 cur.execute(sql, args)57 return list(cur.fetchall()) if cur.description else []58 59 60# A new cluster can take a minute to accept connections after it reports ACTIVE.61for attempt in range(18):62 try:63 with reader_connect(database=False) as conn, conn.cursor() as cur:64 cur.execute('SELECT CURRENT_USER()')65 print('Connected to the reader as', cur.fetchone()[0])66 break67 except s2.OperationalError:68 if attempt == 17:69 raise70 time.sleep(10)
Attach the database read-only. ATTACH DATABASE ... READ ONLY runs on the reader. It copies no data, so it takes seconds, not the minutes a restore would. A rerun finds the database already attached and skips this step. If the reader already has a writable database of the same name, the cell stops instead, and so does every later connection to the reader: the notebook only ever reads from, and tries its write tests on, a read-only attachment.
In [14]:
1with reader_connect(database=False) as conn, conn.cursor() as cur:2 state = reader_attachment(cur)3 if state is None:4 t0 = time.perf_counter()5 cur.execute(f'ATTACH DATABASE {DATABASE} READ ONLY')6 print(f'Attached {DATABASE} to {reader.name} in {time.perf_counter() - t0:.0f} s.')7 elif state == 'READONLY':8 print(f'{DATABASE} is already attached to {reader.name}.')9 require_read_only(cur)10 cur.execute("""SELECT site_name, attach_type FROM information_schema.mv_cloud_attached_databases11 WHERE database_name = %s ORDER BY attach_type DESC""", (DATABASE,))12 for site, kind in cur.fetchall():13 print(f' {site:40s} {kind}')
Every cluster attached to the database is listed: one READWRITE row for the writer, and a READONLY row for each reader. Now read from it. The first run of a report fetches what it needs from object storage into the reader's cache; repeat runs read the cache.
In [15]:
1CLOSE_REPORT = """2 SELECT o.customer, COUNT(*) AS ads_shown, SUM(n.cost_cents) / 100 AS spend_dollars3 FROM notifications n JOIN offers o ON o.offer_id = n.offer_id4 GROUP BY o.customer ORDER BY spend_dollars DESC LIMIT 5"""5 6with reader_connect() as conn, conn.cursor() as cur:7 for run in range(3):8 t0 = time.perf_counter()9 cur.execute(CLOSE_REPORT)10 rows = cur.fetchall()11 print(f'Run {run + 1}: {(time.perf_counter() - t0) * 1000:5.0f} ms')12 13print()14for customer, shown, spend in rows:15 print(f'{customer:16s} {shown:6d} ads ${spend:,.2f}')16print('\nSame counts on both clusters:',17 query('SELECT COUNT(*) FROM notifications') == reader_query('SELECT COUNT(*) FROM notifications'))
Lab notes: attaching
Attaching the 10-million-row database took under half a minute the first time, and seconds when the reader attached it again after a detach. The first report on a fresh reader ran several times slower than its repeats, while the reader filled its cache.
Size a reader for its working set, the data its queries touch: if that does not fit in its cache, queries keep fetching from object storage.
</div>
3. Measure ad serving with reports on the writer, then on the reader.
The ad server's query is small: find the highest bid among the offers a subscriber is targeted by. Theo's close reports are heavy joins over millions of rows. The next cell serves ads on the writer for 30 seconds three times: alone, with four report sessions on the writer, and with the same four sessions on the reader.
In [16]:
1SERVE = """2 SELECT o.offer_id, o.maximum_bid_cents3 FROM subscriber_segments s JOIN offers o ON CONCAT('buyer:', o.customer) = s.segment4 WHERE s.subscriber_id = %s AND s.expires_at > NOW(6) AND o.enabled5 ORDER BY o.maximum_bid_cents DESC LIMIT 1"""6 7REPORTS = [8 """SELECT p.vendor, COUNT(DISTINCT r.domain) AS domains, COUNT(*) AS pairs9 FROM requests r JOIN purchases p ON p.subscriber_id = r.subscriber_id10 GROUP BY p.vendor ORDER BY pairs DESC LIMIT 5""",11 """SELECT SUBSTRING_INDEX(domain, '.', -1) AS tld, COUNT(DISTINCT subscriber_id)12 FROM requests WHERE domain RLIKE '^[a-m].*(box|zz|oo).*' GROUP BY 1""",13]14 15CONNECT = {'writer': connect, 'reader': reader_connect}16 17buyers = [r[0] for r in query("SELECT subscriber_id FROM subscriber_segments WHERE segment LIKE 'buyer:%' LIMIT 2000")]18 19# Each cluster compiles a query shape on first use and caches the data it reads.20# Run every query once on both, so neither lands inside a measurement.21for where in CONNECT:22 with CONNECT[where]() as conn, conn.cursor() as cur:23 for sql in REPORTS:24 cur.execute(sql)25 cur.fetchall()26query(SERVE, (buyers[0],))27 28 29def run_reports(where, stop, done):30 """Run close reports on ``where`` until ``stop`` is set, appending 1 to ``done`` per report."""31 with CONNECT[where]() as conn, conn.cursor() as cur:32 i = 033 while not stop.is_set():34 cur.execute(REPORTS[i % len(REPORTS)])35 cur.fetchall()36 done.append(1)37 i += 138 39 40def serve_ads(reports_on=None, seconds=30, report_threads=4):41 """Serve ads on the writer for ``seconds`` while reports run on ``reports_on``.42 43 Parameters44 ----------45 reports_on : str, optional46 'writer' or 'reader'. With None, no reports run.47 seconds : float, optional48 How long to serve ads.49 report_threads : int, optional50 Number of concurrent report sessions.51 52 Returns53 -------54 dict55 Serving latency percentiles in milliseconds, and the number of reports completed.56 57 """58 stop, done = threading.Event(), []59 reporters = [threading.Thread(target=run_reports, args=(reports_on, stop, done))60 for _ in range(report_threads if reports_on else 0)]61 for r in reporters:62 r.start()63 time.sleep(3 if reports_on else 0)64 latencies = []65 with connect() as conn, conn.cursor() as cur:66 start_reports = len(done)67 end = time.time() + seconds68 while time.time() < end:69 t0 = time.perf_counter()70 cur.execute(SERVE, (random.choice(buyers),))71 cur.fetchall()72 latencies.append((time.perf_counter() - t0) * 1000)73 reports = len(done) - start_reports74 stop.set()75 for r in reporters:76 r.join()77 q = statistics.quantiles(latencies, n=100)78 return {'p50': q[49], 'p95': q[94], 'reports': reports if reports_on else None}79 80 81results = {'Serving alone': serve_ads(),82 'Reports on the writer': serve_ads('writer'),83 'Reports on the reader': serve_ads('reader')}84base = results['Serving alone']85for label, r in results.items():86 reports = '' if r['reports'] is None else f" reports completed: {r['reports']}"87 print(f"{label:24s} p50 {r['p50'] / base['p50']:4.1f}x p95 {r['p95'] / base['p95']:4.1f}x{reports}")
Latency is shown as a multiple of serving alone. With the reports on the writer, they compete with ad serving for the same CPUs, and the slowest ads get two to four times slower. On the reader, they use other CPUs, and ad serving runs as if they were not there.
Lab notes: isolation
Across four runs, ad-serving latency as a multiple of serving alone, with four report sessions:
| p50 | p95 | |
|---|---|---|
| Reports on the writer | 1.2-2.7x | 1.9-4.5x |
| Reports on the reader | 0.9-1.0x | 1.0x |
On a reader the same size as the writer, the reports completed as many times as on the writer; on a reader twice the size, more than twice as many. Compare the previous notebook: a resource pool brought p95 down to about 2x by giving the reports less CPU. A reader brings it to 1x and gives the reports a whole cluster.
</div>
4. Make sure the AI agent cannot write.
Morgan Blaze, Chief Marketing Officer: The board loved it: advertisers will ask our AI agent about their own campaigns. Legal loved it less. The agent must be unable to change anything. Not "it doesn't have the permission". Unable.
In the previous notebook the agent got its own login with only SELECT grants. That still depends on nobody ever granting it more. A read-only attachment does not depend on grants: on the reader, the database itself refuses writes, for every user.
The notebook's own login can write to ad_platform on the writer. Point it at the reader and try every kind of change:
In [17]:
1WRITES = [2 "INSERT INTO offers (offer_id, customer, maximum_bid_cents, budget_cents) VALUES (9999, 'Agent', 1, 1)",3 'UPDATE offers SET budget_cents = budget_cents * 2 WHERE offer_id = 42',4 'DELETE FROM notifications WHERE offer_id = 42',5 'TRUNCATE TABLE subscriber_segments',6 'CREATE TABLE agent_scratch (note TEXT)',7 'ALTER TABLE offers ADD COLUMN agent_note TEXT',8 'DROP TABLE purchases',9 'CREATE TEMPORARY TABLE agent_tmp (note TEXT)',10]11 12with reader_connect() as conn, conn.cursor() as cur:13 for sql in WRITES:14 try:15 cur.execute(sql)16 print(f'ALLOWED {sql}')17 except s2.Error as e:18 print(f'refused {e.errno} {sql.split("(")[0][:60]}')19 cur.execute('SELECT COUNT(*) FROM offers WHERE offer_id = 42')20 print('\nReads still work:', cur.fetchone()[0], 'row for offer 42')
Every write fails with error 2719: the database "is attached as a readonly database" on the reader "and is unavailable for write operations". That covers data changes and schema changes alike. Temporary tables fail too, with 1706, so an agent framework that stages results in a temporary table needs to run that step somewhere else.
Point the agent's connection string at the reader's endpoint, and the worst a bad prompt can do is a slow query on a cluster no customer is waiting on.
In [18]:
1print('Agent endpoint (the reader):', reader.endpoint)
Lab notes: read-only
Writes refused on the reader, for an admin login as for the notebook's: INSERT, UPDATE, DELETE and TRUNCATE (2719, reported by a leaf node), CREATE, ALTER and DROP (2719), and CREATE TEMPORARY TABLE (1706).
</div>
5. Measure how fresh the reader is.
Priya Raman, Finance: If Theo's reports run on a different machine, how old are their numbers? I close on spend charged up to the minute. "Near real time" is not a number I can put in an audit file.
The writer commits a change, then sends its transaction log to the readers asynchronously, and each reader replays it. Measure the gap the way Priya would see it: charge offer 42 on the writer with UPDATE ... RETURNING, which hands back the new balance, then read the reader until it shows that balance.
Measure twice: with the writer idle, then while 8 sessions serve ads and charge budgets on it.
In [19]:
1def staleness(samples=12):2 """Charge offer 42 on the writer and time how long the reader takes to show each new balance.3 4 Parameters5 ----------6 samples : int, optional7 Number of charges to time.8 9 Returns10 -------11 list of float12 Seconds from each commit until the reader returned the new balance, sorted.13 14 """15 gaps = []16 with connect() as w, reader_connect() as r, w.cursor() as wc, r.cursor() as rc:17 for _ in range(samples):18 wc.execute('UPDATE offers SET spend_cents = spend_cents + 1 WHERE offer_id = 42 RETURNING spend_cents')19 balance = wc.fetchone()[0]20 t0 = time.perf_counter()21 while True:22 rc.execute('SELECT spend_cents FROM offers WHERE offer_id = 42')23 if rc.fetchone()[0] >= balance:24 break25 time.sleep(0.05)26 gaps.append(time.perf_counter() - t0)27 time.sleep(0.5)28 return sorted(gaps)29 30 31def ad_traffic(stop, served):32 """Show ads and charge budgets on the writer until ``stop`` is set."""33 with connect() as conn, conn.cursor() as cur:34 while not stop.is_set():35 offer = random.randint(1, 356)36 cur.execute("""INSERT INTO notifications (ts, subscriber_id, offer_id, cost_cents)37 SELECT NOW(6), %s, offer_id, maximum_bid_cents FROM offers WHERE offer_id = %s""",38 (random.choice(buyers), offer))39 cur.execute('UPDATE offers SET spend_cents = spend_cents + 7 WHERE offer_id = %s', (offer,))40 served.append(1)41 42 43def show(label, gaps):44 print(f'{label:34s} min {gaps[0]:4.2f} s median {gaps[len(gaps) // 2]:4.2f} s max {gaps[-1]:4.2f} s')45 46 47show('Writer idle', staleness())48 49stop, served = threading.Event(), []50traffic = [threading.Thread(target=ad_traffic, args=(stop, served)) for _ in range(8)]51for t in traffic:52 t.start()53time.sleep(3)54t0, n0 = time.time(), len(served)55busy = staleness()56rate = (len(served) - n0) / (time.time() - t0)57stop.set()58for t in traffic:59 t.join()60show(f'Writer busy ({rate:,.0f} ads charged/s)', busy)
The gap includes the time to commit on the writer and to read on the reader, so it is an upper bound. SingleStore's objective for Smart Attach is that new data reaches read-only attachments within 1 minute; here it took about a second or less.
Lab notes: freshness
Across three runs of 12 to 15 charges each:
| Writer | Charge visible on the reader after |
|---|---|
| Idle | 0.4 to 1.9 seconds, median 0.7 to 0.9 |
| Busy, 50 to 370 ads charged per second | 0.1 to 0.45 seconds, median about 0.3 |
The reader was fresher while the writer was busy. A reader gives the same consistency as the writer, read committed; it only applies the writer's changes a little later. Each reader replays on its own, so two readers can differ by a moment.
</div>
6. Watch a schema change reach the reader, and size the reader on its own.
Sam Whitfield, Data Engineering: Two things. Finance wants a quarterly target on every offer, so I'm adding a column. Does Theo's cluster get it, or do I file a ticket with myself? And his cluster should be small most of the month and big at close, without anyone touching ad serving.
Schema changes follow the data. DDL runs on the writer and reaches readers through the same log as the data. Add Finance's column on the writer, then read it on the reader:
In [20]:
1def has_target_column(on_reader=False):2 """Return True if offers has the quarter_target_cents column, on the writer or the reader."""3 sql = """SELECT 1 FROM information_schema.columns4 WHERE table_schema = %s AND table_name = 'offers' AND column_name = 'quarter_target_cents'"""5 return bool((reader_query if on_reader else query)(sql, (DATABASE,)))6 7 8if has_target_column():9 query('ALTER TABLE offers DROP COLUMN quarter_target_cents')10 while has_target_column(on_reader=True):11 time.sleep(0.2)12 13query('ALTER TABLE offers ADD COLUMN quarter_target_cents BIGINT NOT NULL DEFAULT 0')14t0 = time.perf_counter()15while not has_target_column(on_reader=True):16 time.sleep(0.1)17print(f'The new column reached the reader {time.perf_counter() - t0:.1f} s after the ALTER committed.')18 19query('UPDATE offers SET quarter_target_cents = budget_cents * 3 WHERE offer_id = 42')20time.sleep(2)21print('Offer 42 on the reader:', reader_query('SELECT customer, quarter_target_cents FROM offers WHERE offer_id = 42'))
Sam files no ticket: new tables and columns arrive on every reader without a step of their own.
Size readers on their own. The writer is sized for ad serving and charging; each reader is sized for its own queries. The one limit is that a reader needs at least one CPU core for every 8 partitions of the database:
In [21]:
1reader.refresh()2print(f'Writer {writer.name}: {writer.size}')3print(f'Reader {reader.name}: {reader.size}')
For the close, Theo's reader can grow, and shrink again afterwards, through the Management API or the portal, because it is a cluster of its own. Set RESIZE_READER = True to try it on the reader this notebook created. The cell grows the reader one size, then shrinks it back, waiting for each change to finish.
In [22]:
1RESIZE_READER = False2 3if RESIZE_READER and created_reader:4 for size in ['S-0', READER_SIZE]:5 t0 = time.time()6 reader.update(size=size, wait_on_active=True, wait_timeout=1800)7 print(f'Reader resized to {reader.size} in {time.time() - t0:.0f} s; '8 f'writer still {clusters.get_workspace(writer.id).size}')9elif RESIZE_READER:10 print(f'{reader.name} was not created by this notebook, so it is not resized.')
Lab notes: schema changes
An added column was queryable on the reader 0.2 to 1.5 seconds after the ALTER committed, and a new table with its rows arrived as fast. Dropped columns disappear the same way.
</div>
7. Detach the reader while ads keep serving.
Morgan Blaze, Chief Marketing Officer: The close is DONE. Turn off whatever we're paying for that we don't need until June. Ads keep running, obviously.
DETACH DATABASE on the reader removes its attachment and nothing else. The writer does not take part, so ad serving carries on. Detach while 8 sessions serve ads and charge budgets on the writer:
In [23]:
1stop, served, errors = threading.Event(), [], []2 3 4def guarded_traffic():5 try:6 ad_traffic(stop, served)7 except Exception as e:8 errors.append(e)9 10 11traffic = [threading.Thread(target=guarded_traffic) for _ in range(8)]12for t in traffic:13 t.start()14time.sleep(3)15 16n0 = len(served)17with reader_connect(database=False) as conn, conn.cursor() as cur:18 require_read_only(cur)19 t0 = time.perf_counter()20 cur.execute(f'DETACH DATABASE {DATABASE}')21 print(f'Detached {DATABASE} from {reader.name} in {time.perf_counter() - t0:.1f} s.')22time.sleep(5)23stop.set()24for t in traffic:25 t.join()26print(f'The writer charged {len(served) - n0} ads meanwhile, with {len(errors)} errors.')27 28with reader_connect(database=False) as conn, conn.cursor() as cur:29 try:30 cur.execute(f'SELECT COUNT(*) FROM {DATABASE}.offers')31 except s2.Error as e:32 print(f'On the reader now: {e.errno} {e.msg}')
Detaching keeps nothing on the reader and deletes nothing: the database lives on with its writer, and attaching it again later is the same one-line ATTACH as in section 2. A cluster with no work can then be suspended or terminated. If this notebook created the reader, terminate it now:
In [24]:
1if created_reader:2 t0 = time.time()3 reader.terminate(wait_on_terminated=True, wait_timeout=1800)4 print(f'Terminated {reader.name} in {time.time() - t0:.0f} s.')5else:6 print(f'{reader.name} was not created by this notebook, so it keeps running.')
8. Clean up.
Drop the database on the writer. If you used an existing cluster as the reader and stopped before section 7, the next cell detaches it first, so the drop leaves no reader holding the database.
In [25]:
1if not created_reader:2 try:3 with reader_connect(database=False) as conn, conn.cursor() as cur:4 if reader_attachment(cur) == 'READONLY':5 cur.execute(f'DETACH DATABASE {DATABASE}')6 print(f'Detached {DATABASE} from {reader.name}.')7 except s2.Error as e:8 print(f'Could not check {reader.name}: {e}')9 10query(f'DROP DATABASE IF EXISTS {DATABASE}')11print(f'Dropped {DATABASE}.')
9. Wrap up.
Five tickets, one database, two clusters:
| Feature | What it is | Use it for | Watch out for |
|---|---|---|---|
| Read-only attachment | A second cluster attached to the same database with ATTACH DATABASE ... READ ONLY; nothing is copied | Reports, dashboards and AI agents that need live data and their own CPUs (ADV-341) | Same region as the writer; the first queries fill the reader's cache, so size it for its working set |
| Writes refused on the reader | Every INSERT, UPDATE, DELETE and DDL fails with error 2719, for every login | SQL you did not write, such as an AI agent's (ADV-342) | Temporary tables fail too (1706) |
| Replay from the writer's log | Readers apply the writer's committed changes about a second later, with the same read-committed consistency | Fresh numbers on a separate cluster (ADV-343) | Readers replay independently, so two readers can differ by a moment |
| DDL that follows the data | Tables and columns created on the writer appear on every reader | One schema to maintain (ADV-344) | Run all DDL on the writer |
| Independent size | Each reader is its own cluster, resized and paid for on its own | Sizing reporting capacity for the close separately from ad serving (ADV-344) | A reader needs at least one core per 8 partitions of the database |
| DETACH DATABASE on the reader | Removes the reader's attachment; the database and the writer carry on | Turning reporting capacity off between closes (ADV-345) | Suspend or terminate the idle cluster to stop paying for it |

Details
About this Template
Isolate read and write workloads, independently size readers, and make new writes available in near real time.
Tags
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.