Operationalize Integrations with Flow and Connectors
Notebook
Note
This notebook requires a Standard or Premium cluster; it does not run on a Free Starter Cluster. The SingleStore Flow APIs are currently a Preview feature. The notebook runs end to end in dry-run mode without a Flow instance.
Demonstrate console setup, Flow APIs, automation, CDC, and commonly used source connectors.
What this notebook demonstrates
| # | Section | What the audience sees |
|---|---|---|
| 0 | Getting started | Install packages, load secrets (Flow endpoint, API key, DB credentials), and choose dry-run or live mode |
| 1 | Console setup | How a Flow on Helios instance is provisioned from the Cloud Portal, and what the checklist looks like |
| 2 | Source connectors | The commonly used sources (MySQL, PostgreSQL, SQL Server, Oracle, Snowflake, MongoDB, any JDBC) and how each one captures change |
| 3 | Flow APIs | A small Python client for the Ingest and XL Ingest REST APIs |
| 4 | Automation | One idempotent function that stands up a full pipeline: connections → tables → schedule → full extract |
| 5 | CDC | Make changes on the source, trigger/await a delta, and prove they landed in SingleStore |
| 6 | Large tables | Parallel, sliced initial load with XL Ingest |
| 7 | Operate it | Schedules, schema sync, freshness checks, and where native Pipelines (Kafka, S3) fit |
Run modes. Every API call goes through one client with a
DRY_RUNswitch. WithDRY_RUN = True(the default) the notebook prints the exact HTTP request it would send, so you can rehearse the whole demo with no Flow instance. Flip it toFalseonce your Flow endpoint and API key are set.
Status note. The Flow APIs are documented by SingleStore as a Preview feature. Endpoint shapes below follow the current Flow on Helios API reference; check the docs before a customer-facing run.
Architecture at a glance
┌──────────────── Sources ────────────────┐ ┌────────── SingleStore Flow (on Helios) ──────────┐ ┌──── SingleStore Helios ────┐
│ MySQL ........ binlog (Log / Continuous)│ │ Ingest schema + data ≤10 GB + ongoing CDC │ │ │
│ PostgreSQL ... logical replication (WAL)│ ─────▶ │ XL Ingest parallel sliced load for big tables │ ─────▶ │ Standard cluster / DB │
│ SQL Server ... Change Tracking or CDC │ │ │ │ (tables w/ PK + shard key │
│ Oracle ....... LogMiner │ │ Control plane: Portal UI · REST API (Bearer) │ │ created automatically) │
│ Snowflake / any JDBC ... full extracts │ └──────────────────────────────────────────────────┘ └────────────────────────────┘
│ MongoDB ...... private preview │ ▲
└─────────────────────────────────────────┘ │ this notebook: FlowClient → provision → CDC check → monitor
Native Pipelines (Kafka, S3, GCS, Azure Blob, …) are the complementary path for streams and files; Flow is the path for operational databases with CDC. Section 7 shows both side by side.
0 · Getting started
Store credentials as Secrets in the SingleStore Portal (Editor → Secrets) rather than in cells. The helper below reads a Portal secret when running inside a SingleStore notebook, falls back to environment variables anywhere else, and finally to the placeholder default.
| Secret name | Used for |
|---|---|
FLOW_API_KEY | Bearer token for the Flow API (Portal → Configuration → API keys) |
FLOW_ENDPOINT | Flow instance endpoint (Portal → Ingestion → Flow → ⋯ → View Details → Endpoint) |
SRC_HOST, SRC_PORT, SRC_USER, SRC_PASSWORD, SRC_DATABASE | Source database |
S2_HOST, S2_USER, S2_PASSWORD | Destination SingleStore cluster |
In [1]:
1# Optional: only needed for the live CDC section (writing to a MySQL source) and destination checks2%pip install --quiet requests pandas singlestoredb pymysql
In [2]:
1import os, json, time, copy, random, string, urllib.parse2from datetime import datetime, timezone3 4import pandas as pd5import requests6 7try:8 from IPython.display import display, Markdown9except ImportError: # running outside Jupyter10 display = print11 Markdown = str12 13def secret(name, default=None):14 """Portal secret -> environment variable -> default."""15 try:16 return get_secret(name) # provided automatically inside SingleStore notebooks17 except Exception:18 return os.environ.get(name, default)19 20# ---------------------------------------------------------------- demo switches21DRY_RUN = True # True = print requests only. Set False to call your live Flow instance.22SOURCE_KIND = "mysql" # mysql | postgres | sqlserver | oracle | snowflake (drives the source connector config)23 24# ---------------------------------------------------------------- Flow on Helios endpoint25# Format: https://gateway.<cell>.svc.singlestore.com/ingest/<flow-id>26# - Ingest API base = <endpoint>/ingest/api/ingest27# - XL Ingest API base = same gateway, /xlingest/<flow-id>/ixl28FLOW_ENDPOINT = secret("FLOW_ENDPOINT", "https://gateway.aws-virginia-8.svc.singlestore.com/ingest/00000000-0000-0000-0000-000000000000")29FLOW_API_KEY = secret("FLOW_API_KEY", "<your-api-key>")30 31# ---------------------------------------------------------------- source (example: MySQL classicmodels)32SRC = dict(33 host = secret("SRC_HOST", "mysql.example.com"),34 port = secret("SRC_PORT", "3306"),35 user = secret("SRC_USER", "bflow_ingest_user"),36 password = secret("SRC_PASSWORD", "<source-password>"),37 database = secret("SRC_DATABASE", "classicmodels"),38)39 40# ---------------------------------------------------------------- destination (SingleStore Helios)41S2 = dict(42 host = secret("S2_HOST", "svc-xxxxxxxx-dml.aws-virginia-8.svc.singlestore.com"),43 port = secret("S2_PORT", "3306"),44 user = secret("S2_USER", "admin"),45 password = secret("S2_PASSWORD", "<s2-password>"),46 database = secret("S2_DATABASE", "classicmodels"),47)48 49DEMO_TABLES = ["customers", "orders", "orderdetails", "products"]50 51print(f"DRY_RUN={DRY_RUN} | source={SOURCE_KIND} {SRC['host']}:{SRC['port']}/{SRC['database']} -> SingleStore {S2['host']}")
1 · Console setup (Flow on Helios)
Flow on Helios is fully managed: there is nothing to install, and the instance is billed only while it runs. The console path is the fastest way to show "zero to replicating" live.
Walkthrough to show on screen
Cloud Portal → Ingestion → Load Data.
Pick a source tile: MySQL by Flow, PostgreSQL by Flow, Oracle by Flow, SQL Server by Flow, or Snowflake by Flow.
Select destination: choose the cluster (must be the Standard type) and database; create or reuse a named connection (no leading digit, no special characters except
_).Open Dashboard → choose Ingest (≤ 10 GB per table, plus ongoing CDC) or XL Ingest (larger tables) from the top-right drop-down.
Complete the Checklist: Setup Source → Setup Destination → Setup Tables → Setup Schedule.
Operations tab → start the pipeline. It then runs on the chosen schedule.
Monitor: Operations (re-sync, schema changes), Settings, Reports (per-table performance by day/month), Logs (extract/load progress).
Lifecycle: suspend/resume the instance to stop compute; scale it up or down as volume changes.
Before the demo — network
Find the outbound IPs of your Helios cluster and add them to the source's firewall / security group / allowed-IP list.
Self-hosted or on-prem sources must be reachable from the internet for Flow on Helios. If the source sits deep on-prem with high volume, the self-managed Flow deployment (runs next to the source) is the better fit.
Then grab two values for the API sections: the instance Endpoint (Ingestion → Flow → ⋯ → View Details) and an API key (Configuration → API keys → Create API key; it's shown only once).
💡 Talk track: "Everything you just clicked is also an API call. The rest of this notebook does the same thing from code, so it can go into CI/CD, Terraform wrappers, or an onboarding script that spins up a pipeline per tenant."
2 · Commonly used source connectors
Flow's connector type decides how change is captured. Picking the right one is the main design decision per source.
In [3]:
1CONNECTORS = pd.DataFrame([2 # source, type code, capture mechanism, CDC?, default port, notes3 ("MySQL 5.1+", "rds.mysqlc", "Binlog – Continuous", "Yes", 3306, "Real-time CDC; recommended for MySQL / RDS / Aurora"),4 ("MySQL 5.1+", "rds.mysql", "Binlog – Log (polled)", "Yes", 3306, "CDC on the configured schedule"),5 ("PostgreSQL 9.4+", "rds.pgres", "Logical replication (WAL)", "Yes", 5432, "Needs wal_level=logical + replication slot"),6 ("SQL Server", "rds.mscdcm", "SQL Server CDC", "Yes", 1433, "Requires SQL Server Agent running"),7 ("SQL Server", "rds.msadbctm", "Change Tracking", "Yes", 1433, "Lighter weight than CDC"),8 ("SQL Server", "rds.msfull", "Full extracts", "No", 1433, "Snapshot only"),9 ("Oracle 19c", "rds.oracle11lmc19", "Continuous LogMiner", "Yes", 1521, "ARCHIVELOG + supplemental logging"),10 ("Oracle", "rds.oracle11lfm", "Fast LogMiner", "Yes", 1521, "Also RAC / PDB variants"),11 ("Oracle", "rds.oraclets", "Timestamps", "Yes*",1521, "*Incremental by timestamp column"),12 ("MongoDB / Atlas", "rds.mongo / rds.mongoatlas", "Change streams", "Yes", 27017,"Private preview"),13 ("Snowflake / any JDBC", "rds.jdbcfe", "Full extracts via JDBC", "No", None, "Snowflake JDBC is GA; other JDBC sources are preview"),14], columns=["Source", "Flow type", "Capture mechanism", "CDC", "Port", "Notes"])15 16display(CONNECTORS)17 18# The connector picked for this run19SOURCE_TYPE = {20 "mysql": "rds.mysqlc",21 "postgres": "rds.pgres",22 "sqlserver": "rds.mscdcm",23 "oracle": "rds.oracle11lmc19",24 "snowflake": "rds.jdbcfe",25}[SOURCE_KIND]26print("Using Flow source type:", SOURCE_TYPE)
2.1 · Preparing each source for CDC
Show the one that matches your audience; the others are reference. Run these on the source, not in SingleStore.
In [4]:
1SOURCE_PREP = {2"mysql": """3-- my.cnf / RDS or Aurora parameter group, then restart4-- server_id=1 log_bin=/var/lib/mysql/binlog binlog_format=ROW5-- binlog_row_image=FULL binlog_checksum=NONE (or CRC32)6-- binlog_expire_logs_seconds=604800 -- 7 days; MySQL 8.2+7CREATE USER 'bflow_ingest_user' IDENTIFIED BY '<password>';8GRANT SELECT, REPLICATION CLIENT, REPLICATION SLAVE, SHOW DATABASES, PROCESS ON *.* TO 'bflow_ingest_user';9-- verify10SHOW VARIABLES WHERE Variable_name IN ('log_bin','binlog_format','binlog_row_image','binlog_checksum');11""",12"postgres": """13-- postgresql.conf, then restart14-- wal_level = logical max_replication_slots >= tasks max_wal_senders > 1 wal_sender_timeout = 015-- pg_hba.conf: host replication all <flow-outbound-ip>/32 md516SELECT pg_create_logical_replication_slot('bflow_replication_slot', 'test_decoding');17-- Flow user needs replication role (+ superuser per current docs) and read access to replicated tables18-- Remember: drop unused slots, or WAL accumulates19""",20"sqlserver": """21-- Option A: SQL Server CDC (type rds.mscdcm) -- SQL Server Agent must be running22USE <database_name>;23EXEC sys.sp_cdc_enable_db;24EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'<table>', @role_name = NULL, @supports_net_changes = 0;25EXEC sys.sp_cdc_change_job @job_type = N'cleanup', @retention = 10080; -- minutes (default is 3 days)26 27-- Option B: Change Tracking (type rds.msadbctm)28ALTER DATABASE <database_name> SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 7 DAYS, AUTO_CLEANUP = ON);29ALTER TABLE <table> ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = ON);30GRANT VIEW SERVER STATE TO <login>;31GRANT VIEW CHANGE TRACKING ON <schema>.<table> TO <user>;32""",33"oracle": """34-- Must be in ARCHIVELOG mode: SELECT log_mode FROM V$DATABASE;35ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS;36ALTER TABLE <schema>.<table> ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS;37-- (Amazon RDS: exec rdsadmin.rdsadmin_util.alter_supplemental_logging('ADD','ALL');38-- exec rdsadmin.rdsadmin_util.set_configuration('archivelog retention hours', 24);)39GRANT CREATE SESSION, LOGMINING, SELECT ANY TRANSACTION, EXECUTE_CATALOG_ROLE TO <user>;40GRANT SELECT ON V_$ARCHIVED_LOG TO <user>; GRANT SELECT ON V_$LOGMNR_CONTENTS TO <user>;41GRANT SELECT ON V_$LOGMNR_LOGS TO <user>; GRANT SELECT ON DBA_OBJECTS TO <user>;42GRANT EXECUTE ON DBMS_LOGMNR TO <user>;43-- 19c continuous mining also: V_$DATABASE, V_$LOG, V_$LOGFILE44""",45"snowflake": """46-- Full extracts only (no CDC). Flow user needs SELECT on each table:47GRANT SELECT ON TABLE <db>.<schema>.<table> TO ROLE <flow_role>;48""",49}50print(SOURCE_PREP[SOURCE_KIND])
3 · The Flow APIs
Flow exposes two REST APIs, both authenticated with Authorization: Bearer <API key>:
| API | Base URL (Flow on Helios) | Purpose |
|---|---|---|
| Ingest | https://gateway.<cell>.svc.singlestore.com/ingest/<flow-id>/ingest/api/ingest | Connections, schedule, table selection, operations (full / delta / syncstruct / syncnew) |
| XL Ingest | https://gateway.<cell>.svc.singlestore.com/xlingest/<flow-id>/ixl | Slice large tables and load slices in parallel |
Two conventions worth pointing out to the audience:
Connection payloads are arrays of
{"name": ..., "value": ...}pairs, not plain objects.Save endpoints (
PATCH) return 204 and do not validate; always follow with the matching/testcall.
The self-managed Flow app exposes the same paths at http://<host>:<port>/ingest/api/ingest and /ixl (no Bearer token). The client below supports both.
In [5]:
1class FlowError(RuntimeError):2 pass3 4 5class FlowClient:6 """Thin client for the SingleStore Flow Ingest + XL Ingest APIs (Preview)."""7 8 SECRET_KEYS = {"pwd", "pwd2"}9 10 def __init__(self, endpoint, api_key=None, dry_run=True, timeout=60, verbose=True):11 self.endpoint = endpoint.rstrip("/")12 self.ingest_base = f"{self.endpoint}/ingest/api/ingest"13 # Helios: .../ingest/<flow-id> -> .../xlingest/<flow-id>/ixl ; self-managed: <host>/ixl14 if "/ingest/" in self.endpoint:15 gw, flow_id = self.endpoint.rsplit("/ingest/", 1)16 self.xl_base = f"{gw}/xlingest/{flow_id}/ixl"17 else:18 self.xl_base = f"{self.endpoint}/ixl"19 self.api_key, self.dry_run, self.timeout, self.verbose = api_key, dry_run, timeout, verbose20 self.session = requests.Session()21 self.history = [] # audit trail of every call (great for the demo)22 23 # ------------------------------------------------------------------ plumbing24 def _headers(self):25 h = {"Content-Type": "application/json", "Accept": "application/json"}26 if self.api_key:27 h["Authorization"] = f"Bearer {self.api_key}"28 return h29 30 @classmethod31 def _mask(cls, body):32 if isinstance(body, list):33 return [{**p, "value": "***"} if p.get("name") in cls.SECRET_KEYS else p for p in body]34 return body35 36 def _call(self, method, url, body=None, dry_result=None):37 entry = {"ts": datetime.now(timezone.utc).strftime("%H:%M:%S"), "method": method,38 "path": ("[XL] " + url.split("/ixl", 1)[1]) if "/ixl" in url39 else (url.replace(self.ingest_base, "") or "/"), "status": None}40 if self.verbose:41 print(f"→ {method} {url}")42 if body is not None:43 print(" " + json.dumps(self._mask(body)))44 if self.dry_run:45 entry["status"] = "dry-run"46 self.history.append(entry)47 return copy.deepcopy(dry_result) if dry_result is not None else {"success": True, "dry_run": True}48 49 r = self.session.request(method, url, headers=self._headers(),50 data=None if body is None else json.dumps(body), timeout=self.timeout)51 entry["status"] = r.status_code52 self.history.append(entry)53 if r.status_code >= 400:54 raise FlowError(f"{method} {url} -> HTTP {r.status_code}: {r.text[:500]}")55 if r.status_code == 204 or not r.content:56 return {"success": True}57 try:58 data = r.json()59 except ValueError:60 return {"success": True, "raw": r.text}61 # Flow reports many failures as HTTP 200 + success:false62 if isinstance(data, dict) and data.get("success") is False:63 msgs = "; ".join(m.get("message", "") for m in data.get("messageList", [])) or data.get("message", "")64 raise FlowError(f"{method} {url} -> {msgs or data}")65 return data66 67 @staticmethod68 def _pairs(cfg):69 return [{"name": k, "value": str(v)} for k, v in cfg.items() if v is not None]70 71 @staticmethod72 def connection(host, port, user, password, type_, db=None, drv=None, url=None):73 # pwd2 (confirmation) is still accepted by the API; harmless if the server ignores it74 return dict(host=host, port=port, uid=user, pwd=password, pwd2=password, type=type_, db=db, drv=drv, url=url)75 76 # ------------------------------------------------------------------ Ingest: connections77 def save_source(self, cfg): return self._call("PATCH", f"{self.ingest_base}/conn-src", self._pairs(cfg))78 def test_source(self, cfg): return self._call("POST", f"{self.ingest_base}/conn-src/test", self._pairs(cfg))79 def get_source(self): return self._call("GET", f"{self.ingest_base}/conn-src",80 dry_result=[{"name": "status", "value": "Y"}, {"name": "type", "value": SOURCE_TYPE}])81 def save_destination(self, cfg): return self._call("PATCH", f"{self.ingest_base}/conn-dst", self._pairs(cfg))82 def test_destination(self, cfg): return self._call("POST", f"{self.ingest_base}/conn-dst/test", self._pairs(cfg))83 def get_destination(self): return self._call("GET", f"{self.ingest_base}/conn-dst",84 dry_result=[{"name": "status", "value": "Y"}, {"name": "type", "value": "rds.sstorem"}])85 86 # ------------------------------------------------------------------ Ingest: schedule87 def set_schedule(self, type_="periodic", duration=None, offset=None, week_flags=None):88 body = {"type": type_}89 if duration: body["duration"] = duration90 if offset: body["offset"] = offset91 if week_flags: body["weekFlags"] = week_flags92 return self._call("PATCH", f"{self.ingest_base}/config-sched", body)93 94 def get_schedule(self):95 return self._call("GET", f"{self.ingest_base}/config-sched",96 dry_result={"type": "periodic", "duration": "0d00h01m00s", "offset": "0d00h00m", "isScheduled": True, "weekFlags": None})97 98 # ------------------------------------------------------------------ Ingest: tables99 def list_tables(self, database, schema):100 fake = [{"name": t, "selected": False, "id": t} for t in101 ["customers", "employees", "offices", "orderdetails", "orders", "payments", "productlines", "products"]]102 return self._call("GET", f"{self.ingest_base}/list-db/{database}/{schema}", dry_result=fake)103 104 def select_table(self, database, schema, table, select=True):105 return self._call("PATCH", f"{self.ingest_base}/config-tab/{database}/{schema}/{table}",106 {"select": "Y" if select else "N"})107 108 # ------------------------------------------------------------------ Ingest: operations109 def run(self, operation):110 assert operation in {"full", "delta", "syncstruct", "syncnew"}, operation111 labels = {"full": "Full Extract", "delta": "Delta", "syncstruct": "Synchronize Structure", "syncnew": "Sync New Tables"}112 return self._call("POST", f"{self.ingest_base}/ops/extract/{operation}",113 dry_result={"success": True, "message": f"{labels[operation]} requested"})114 115 # ------------------------------------------------------------------ XL Ingest116 @staticmethod117 def xl_table_id(database, schema, table):118 return f"{database}:{schema}.{table}"119 120 def xl_configure(self, table_id, slice_col, slice_bounds=None, slice_count=None, prefix_size=None, where=""):121 """Manual slicing: pass slice_bounds. Automatic slicing: pass slice_count + prefix_size."""122 body = {"id": table_id, "select": True, "sliceCol": slice_col, "where": where,123 "sliceList": [{"name": str(b)} for b in (slice_bounds or [])],124 "prefixSize": "" if prefix_size is None else prefix_size,125 "sliceCount": "" if slice_count is None else slice_count}126 return self._call("PATCH", f"{self.xl_base}?cmd=tdp", body)127 128 def xl_transfer(self, table_id):129 tab = urllib.parse.quote(table_id, safe=".")130 n = 4131 return self._call("POST", f"{self.xl_base}?cmd=tgsy&tab={tab}",132 dry_result={"isRunning": True, "type": "SY", "tasksComplete": 0, "table": table_id, "tasksTotal": n})133 134 # ------------------------------------------------------------------ demo helpers135 def audit(self):136 return pd.DataFrame(self.history)137 138 139flow = FlowClient(FLOW_ENDPOINT, FLOW_API_KEY, dry_run=DRY_RUN)140print("Ingest API :", flow.ingest_base)141print("XL Ingest API:", flow.xl_base)
3.1 · Connections — save, then test
Flow keeps one source and one destination per instance. The destination type is always rds.sstorem (SingleStore).
In [6]:
1src_cfg = FlowClient.connection(SRC["host"], SRC["port"], SRC["user"], SRC["password"], SOURCE_TYPE, db=SRC["database"])2dst_cfg = FlowClient.connection(S2["host"], S2["port"], S2["user"], S2["password"], "rds.sstorem", db=S2["database"])3 4flow.save_source(src_cfg)5print("source test:", flow.test_source(src_cfg), "\n")6 7flow.save_destination(dst_cfg)8print("destination test:", flow.test_destination(dst_cfg))
In [7]:
1# Read back what Flow stored. Passwords come back masked; status "Y" = last test succeeded.2def pairs_to_dict(pairs):3 return {p["name"]: p["value"] for p in pairs} if isinstance(pairs, list) else pairs4 5display(pd.DataFrame([pairs_to_dict(flow.get_source()), pairs_to_dict(flow.get_destination())], index=["source", "destination"]))
3.2 · Discover and select tables
list-db/{database}/{schema} returns every table plus whether it's selected. For MySQL the database and schema are typically the same name; for SQL Server/Postgres the schema is usually dbo / public.
In [8]:
1SCHEMA = {"mysql": SRC["database"], "postgres": "public", "sqlserver": "dbo"}.get(SOURCE_KIND, SRC["database"])2 3tables = pd.DataFrame(flow.list_tables(SRC["database"], SCHEMA))4display(tables)5 6for t in DEMO_TABLES:7 flow.select_table(SRC["database"], SCHEMA, t)
3.3 · Schedule
| type | duration format | Example | Use when |
|---|---|---|---|
manual | – | {"type":"manual"} | Demos, one-off migrations, orchestrator-triggered deltas |
auto | – | {"type":"auto"} | Let Flow run continuously |
periodic | DdHHhMMmSSs | 0d00h01m00s | Near-real-time CDC every N minutes |
daily | HHhMMm | 02h30m | Nightly batch |
weekly | HHhMMm + weekFlags (Sun→Sat) | NYYYYYN | Weekday-only loads |
In [9]:
1flow.set_schedule("periodic", duration="0d00h01m00s", offset="0d00h00m") # every minute for the demo2display(flow.get_schedule())3 4# Other patterns (uncomment to show):5# flow.set_schedule("daily", duration="02h30m")6# flow.set_schedule("weekly", duration="06h00m", week_flags="NYYYYYN")7# flow.set_schedule("manual")
3.4 · Initial load
POST /ops/extract/full creates the schema in SingleStore (primary and shard keys included) and copies every selected table. The call returns immediately; progress shows in the dashboard Logs tab — keep it open on a second screen.
In [10]:
1print(flow.run("full"))
4 · Automation: one call to stand up a pipeline
The cells above, packaged as an idempotent function you can drop into a CI job, an Airflow/Dagster task, or a tenant-onboarding script. Re-running it is safe: saves are upserts and table selection is declarative.
In [11]:
1def provision_pipeline(flow, source_cfg, dest_cfg, database, schema, tables,2 schedule=("periodic", "0d00h05m00s"), initial_load=True):3 """Configure + validate + start a Flow Ingest pipeline. Returns a summary dict."""4 steps = []5 def step(name, fn, *a, **kw):6 t0 = time.time()7 out = fn(*a, **kw)8 steps.append({"step": name, "seconds": round(time.time() - t0, 2), "result": str(out)[:80]})9 return out10 11 step("save source", flow.save_source, source_cfg)12 step("test source", flow.test_source, source_cfg) # raises FlowError on failure13 step("save destination", flow.save_destination, dest_cfg)14 step("test destination", flow.test_destination, dest_cfg)15 16 available = {t["name"] for t in step("list tables", flow.list_tables, database, schema)}17 missing = set(tables) - available18 if missing:19 raise FlowError(f"Tables not found on source: {sorted(missing)}")20 for t in tables:21 step(f"select {t}", flow.select_table, database, schema, t)22 23 stype, dur = schedule24 step("set schedule", flow.set_schedule, stype, duration=dur)25 if initial_load:26 step("full extract", flow.run, "full")27 return pd.DataFrame(steps)28 29 30quiet = FlowClient(FLOW_ENDPOINT, FLOW_API_KEY, dry_run=DRY_RUN, verbose=False)31display(provision_pipeline(quiet, src_cfg, dst_cfg, SRC["database"], SCHEMA, DEMO_TABLES,32 schedule=("periodic", "0d00h01m00s")))
Patterns to mention
GitOps: keep
{source, tables, schedule}per pipeline in YAML; a CI job callsprovision_pipelineon merge.Secrets: API keys and DB passwords come from the Portal secret store / your vault — never from the repo.
Many sources: one Flow instance = one source → one destination. Fan out by creating one instance per source and looping over their endpoints.
Audit: every call is recorded; see below.
In [12]:
1display(flow.audit().tail(15))
5 · CDC in action
The demo loop:
Snapshot row counts in SingleStore.
Make inserts, updates and a delete on the source.
Wait for the schedule (or force a
delta).Show the changes in SingleStore.
With DRY_RUN = True the source/destination cells are skipped and the narrative is printed instead.
In [13]:
1import contextlib2 3@contextlib.contextmanager4def s2_conn():5 import singlestoredb as s26 try:7 conn = s2.connect(connection_url) # defined automatically inside SingleStore notebooks8 except NameError:9 conn = s2.connect(host=S2["host"], port=int(S2["port"]), user=S2["user"],10 password=S2["password"], database=S2["database"])11 try:12 yield conn13 finally:14 conn.close()15 16def s2_query(sql, params=None):17 with s2_conn() as c, c.cursor() as cur:18 cur.execute(sql, params)19 cols = [d[0] for d in cur.description] if cur.description else []20 return pd.DataFrame(cur.fetchall(), columns=cols)21 22def dest_counts(tables=DEMO_TABLES):23 if DRY_RUN:24 return pd.DataFrame({"table": tables, "rows": ["(dry-run)"] * len(tables)})25 return pd.concat([s2_query(f"SELECT '{t}' AS `table`, COUNT(*) AS `rows` FROM `{S2['database']}`.`{t}`")26 for t in tables], ignore_index=True)27 28before = dest_counts()29display(before)
In [14]:
1# Generate change on the SOURCE (MySQL example). Uses a tagged customer so the demo is easy to find and clean up.2DEMO_TAG = "FLOWDEMO-" + "".join(random.choices(string.ascii_uppercase, k=4))3DEMO_CUSTOMER = 990000 + random.randint(0, 9999)4 5source_changes = [6 ("INSERT customers", f"""INSERT INTO customers (customerNumber, customerName, contactLastName, contactFirstName,7 phone, addressLine1, city, country, creditLimit)8 VALUES ({DEMO_CUSTOMER}, '{DEMO_TAG} Corp', 'Demo', 'Flow', '555-0100',9 '1 Pipeline Way', 'New York', 'USA', 50000.00)"""),10 ("UPDATE customers", f"UPDATE customers SET creditLimit = 75000.00 WHERE customerNumber = {DEMO_CUSTOMER}"),11 ("UPDATE products", "UPDATE products SET quantityInStock = quantityInStock - 1 WHERE productCode = 'S10_1678'"),12]13 14if DRY_RUN or SOURCE_KIND != "mysql":15 for label, sql in source_changes:16 print(f"[would run on source] {label}:\n {' '.join(sql.split())}\n")17else:18 import pymysql19 with pymysql.connect(host=SRC["host"], port=int(SRC["port"]), user=SRC["user"], password=SRC["password"],20 database=SRC["database"], autocommit=True) as src:21 with src.cursor() as cur:22 for label, sql in source_changes:23 cur.execute(sql)24 print(f"✔ {label} ({cur.rowcount} row)")25change_made_at = datetime.now(timezone.utc)
In [15]:
1# Don't want to wait for the schedule? Force a delta now.2print(flow.run("delta"))
In [16]:
1def wait_for_change(timeout_s=180, poll_s=10):2 """Poll SingleStore until the demo row shows the updated value. Returns observed replication lag."""3 if DRY_RUN:4 print("(dry-run) would poll SingleStore for", DEMO_TAG)5 return None6 deadline = time.time() + timeout_s7 while time.time() < deadline:8 df = s2_query(f"SELECT customerNumber, customerName, creditLimit FROM `{S2['database']}`.customers "9 f"WHERE customerNumber = %s", (DEMO_CUSTOMER,))10 if len(df) and float(df.creditLimit.iloc[0]) == 75000.0:11 lag = (datetime.now(timezone.utc) - change_made_at).total_seconds()12 display(df)13 print(f"✔ change visible in SingleStore after ~{lag:.0f}s")14 return lag15 print("…waiting"); time.sleep(poll_s)16 raise TimeoutError("Change not visible yet — check the Logs tab in the Flow dashboard")17 18lag = wait_for_change()19display(dest_counts())
In [17]:
1# Delete on the source -> delete in SingleStore (also cleans up the demo row)2cleanup_sql = f"DELETE FROM customers WHERE customerNumber = {DEMO_CUSTOMER}"3if DRY_RUN or SOURCE_KIND != "mysql":4 print("[would run on source]", cleanup_sql)5else:6 with pymysql.connect(host=SRC["host"], port=int(SRC["port"]), user=SRC["user"], password=SRC["password"],7 database=SRC["database"], autocommit=True) as src, src.cursor() as cur:8 cur.execute(cleanup_sql); print("✔ deleted on source; it will disappear from SingleStore on the next delta")
5.1 · Schema changes
When the source table changes shape, syncstruct pushes the new structure to SingleStore. Recent Flow releases also detect column adds/drops during CDC for MySQL and PostgreSQL automatically (schema evolution), so syncstruct is mostly needed for other sources or for an explicit, controlled sync.
When someone adds a brand-new table on the source, select it and call syncnew to load just that table without re-running a full extract.
In [18]:
1# e.g. after: ALTER TABLE customers ADD COLUMN loyaltyTier VARCHAR(16);2print(flow.run("syncstruct"))3 4# e.g. after creating a new table 'returns' on the source:5flow.select_table(SRC["database"], SCHEMA, "payments")6print(flow.run("syncnew"))
6 · Large tables with XL Ingest
Ingest handles tables up to ~10 GB. Beyond that, XL Ingest splits the initial copy into slices on a column and loads them in parallel. It is resilient to restarts of the network, Flow, source or destination — a failed slice is retried, not the whole table. Ongoing CDC is still done by Ingest.
Order of operations
In Ingest, select the big table and enable Skip Initial Extract for it (dashboard → Tables).
Run a full extract in Ingest — this copies only the schema for that table.
Configure slices in XL Ingest (
cmd=tdp) and start the transfer (cmd=tgsy).
In [19]:
1BIG_TABLE = flow.xl_table_id("default", SCHEMA, "orderdetails") # format: <db>:<schema>.<table>2 3# Option A – manual slices: boundaries on a numeric/date key4flow.xl_configure(BIG_TABLE, slice_col="orderNumber",5 slice_bounds=[10200, 10300, 10400])6 7# Option B – automatic slices (pick one option per table)8# flow.xl_configure(BIG_TABLE, slice_col="orderNumber", slice_count=8, prefix_size=2)9 10status = flow.xl_transfer(BIG_TABLE)11display(status)12if status.get("error"):13 print("⚠", status["error"])14else:15 print(f"{status['tasksComplete']}/{status['tasksTotal']} slices complete — progress is visible in the XL Ingest dashboard")
Choosing a slice column: an indexed, evenly distributed key (order id, created date). Aim for slices of a few GB each; use where to skip archived rows (e.g. "created_at >= '2024-01-01'").
7 · Operating integrations
7.1 · Freshness and reconciliation from SingleStore
Flow's dashboard covers pipeline health. Applications usually also want a data-level check from the destination side. A simple reconciliation compares source and destination counts per table.
In [20]:
1def reconcile(tables=DEMO_TABLES):2 if DRY_RUN or SOURCE_KIND != "mysql":3 return pd.DataFrame({"table": tables, "source_rows": "-", "dest_rows": "-", "match": "(dry-run)"})4 import pymysql5 rows = []6 with pymysql.connect(host=SRC["host"], port=int(SRC["port"]), user=SRC["user"], password=SRC["password"],7 database=SRC["database"]) as src, src.cursor() as cur:8 for t in tables:9 cur.execute(f"SELECT COUNT(*) FROM `{t}`"); s = cur.fetchone()[0]10 d = int(s2_query(f"SELECT COUNT(*) AS n FROM `{S2['database']}`.`{t}`").n.iloc[0])11 rows.append({"table": t, "source_rows": s, "dest_rows": d, "match": "✔" if s == d else "✗"})12 return pd.DataFrame(rows)13 14display(reconcile())
In [21]:
1# Health check you can schedule (e.g. as a SingleStore scheduled notebook job) and alert on.2def health_check(flow):3 src, dst = pairs_to_dict(flow.get_source()), pairs_to_dict(flow.get_destination())4 sched = flow.get_schedule()5 checks = {6 "source connection OK": src.get("status") == "Y",7 "destination connection OK": dst.get("status") == "Y",8 "schedule active": bool(sched.get("isScheduled")),9 }10 for k, ok in checks.items():11 print(("✔ " if ok else "✗ ") + k)12 return all(checks.values())13 14health_check(flow)
Pair this with the built-in pieces:
Monitor Flow on Helios with Alerts — configure alerting on the instance in the Portal.
Reports tab — per-table load volume and timing by day/month.
Suspend/Resume and Scale — control cost and throughput.
Schedule this notebook as a Job (Notebooks → Schedule) to run
health_check+reconcileevery N minutes.
7.2 · Where native Pipelines fit
| Need | Use |
|---|---|
| Replicate an operational DB (MySQL/Postgres/SQL Server/Oracle) with CDC | Flow (this notebook) |
| One-time migration of a large DB | Flow + XL Ingest |
| Event streams (Kafka, Confluent, Redpanda) | Pipelines LOAD DATA KAFKA |
| Files in object storage (S3, GCS, Azure Blob) | Pipelines LOAD DATA S3 / GCS / AZURE |
The older SQL-native "CDC-in" pipelines for MySQL (
CREATE LINK … AS MYSQL+CREATE TABLES AS INFER PIPELINE) are deprecated in the SingleStore docs. Position Flow as the CDC path going forward.
The cell below shows the shape of a native Kafka and S3 pipeline for contrast. It is printed by default; set RUN_PIPELINE_SQL = True and fill in real broker/bucket values to run it.
In [22]:
1RUN_PIPELINE_SQL = False2 3PIPELINE_SQL = f"""4CREATE TABLE IF NOT EXISTS clickstream (5 event_id BIGINT, customer_id BIGINT, event_type VARCHAR(32), ts DATETIME(6),6 SORT KEY (ts), SHARD KEY (customer_id)7);8 9CREATE OR REPLACE PIPELINE clickstream_kafka AS10 LOAD DATA KAFKA '<broker-host>:9092/clickstream'11 INTO TABLE clickstream12 FORMAT JSON (event_id <- id, customer_id <- customer_id, event_type <- type, ts <- ts);13 14CREATE OR REPLACE PIPELINE orders_archive_s3 AS15 LOAD DATA S3 '<bucket>/orders/*.csv'16 CONFIG '{{"region": "us-east-1"}}'17 CREDENTIALS '{{"aws_access_key_id": "<key>", "aws_secret_access_key": "<secret>"}}'18 INTO TABLE orders19 FIELDS TERMINATED BY ',' IGNORE 1 LINES;20 21START PIPELINE clickstream_kafka;22"""23 24if RUN_PIPELINE_SQL and not DRY_RUN:25 with s2_conn() as c, c.cursor() as cur:26 for stmt in [s for s in PIPELINE_SQL.split(";") if s.strip()]:27 cur.execute(stmt)28 display(s2_query("SELECT pipeline_name, state FROM information_schema.pipelines"))29else:30 print(PIPELINE_SQL)
Wrap-up
What we showed
Console: Load Data → source tile → destination → dashboard checklist → start, with no infrastructure to run.
Connectors: one
typeper capture mechanism — binlog, WAL, SQL Server CDC / Change Tracking, LogMiner, JDBC full extracts.APIs: a ~150-line client covering connections, tables, schedule, operations and XL Ingest.
Automation:
provision_pipeline()turns a pipeline into code you can version, review and re-run.CDC: insert/update/delete on the source show up in SingleStore within one schedule interval, verified from the destination side.
Suggested next steps for the audience
Point the notebook at a real source; set
DRY_RUN = False.Move
provision_pipelineinto CI with secrets from your vault.Schedule
health_check+reconcileas a notebook job and wire alerts.
References (SingleStore docs)
Load Data with SingleStore Flow on Helios — https://docs.singlestore.com/cloud/load-data/load-data-with-singlestore-flow-on-helios/
Use Flow on Helios — https://docs.singlestore.com/cloud/load-data/load-data-with-singlestore-flow-on-helios/use-flow-on-helios/
Source Database Setup — https://docs.singlestore.com/cloud/load-data/load-data-with-singlestore-flow-on-helios/singlestore-ingest/source-database-setup/
Flow on Helios API (auth, Ingest, XL Ingest) — https://docs.singlestore.com/cloud/load-data/load-data-with-singlestore-flow-on-helios/flow-on-helios-api/
Flow release notes — https://docs.singlestore.com/cloud/load-data/load-data-with-singlestore-flow/singlestore-flow-release-notes/
In [23]:
1# Final audit trail of every Flow API call made in this session2display(flow.audit())

Details
About this Template
Demonstrate console setup, Flow APIs, automation, CDC, and commonly used source connectors.
This Notebook can be run in Standard and Enterprise deployments.
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.