Before you beginReview the planned failover and failback runbook
1–3 · Set business requirements and create the scratch dataset
Maple Market needs a verified daily sales report by 08:00 UTC. The example delivery agreement measures on-time verified batches. The regional recovery targets are a 10-minute RPO and a 20-minute RTO. An on-time report contains the expected distinct orders and verified amounts. The fictional clock in the incident lesson illustrates a real delivery deadline. The runnable fixture instead sets B101 due in one hour and B102 due five minutes before setup so both paths can be checked in the same lab.
Use one authorized test account, a lab owner with CREATE DATABASE or an approved existing empty scratch database and permission to create its schema, plus an approved warehouse. Replace MAPLE_WH where required. For the task, the owner also needs account EXECUTE TASK, CREATE TASK on the schema, and warehouse USAGE. Run the single-account lab in a dedicated session with no transaction open. If using a different database, update every qualified reference. Do not reuse a test schema containing earlier attempts.
The source table represents rows already received from upstream. EXPECTED_BATCHES represents the source owner’s delivery list and keeps the deadline and cutoff even if no rows arrive. SALES_TARGET holds checked orders. BATCH_AUDIT stores attempts, ALERT_OUTBOX holds deduplicated late cases, and DR_MARKERS is reserved for an authorized recovery test.
| BATCH_ID | ORDER_ID | AMOUNT |
|---|---|---|
| B101 | 701 | 100.00 |
| B101 | 702 | 50.00 |
| B102 | 703 | 75.00 |
| B102 | 704 | NULL |
CREATE DATABASE LS_M20_OPS_LAB;
CREATE SCHEMA LS_M20_OPS_LAB.OPS;
USE SCHEMA LS_M20_OPS_LAB.OPS;
USE WAREHOUSE MAPLE_WH;
ALTER SESSION SET TIMEZONE = 'UTC';
CREATE TABLE EXPECTED_BATCHES (
batch_id VARCHAR NOT NULL,
due_at TIMESTAMP_LTZ NOT NULL,
source_cutoff TIMESTAMP_LTZ NOT NULL,
expected_rows NUMBER NOT NULL
);
CREATE TABLE SOURCE_ORDERS (batch_id VARCHAR NOT NULL, order_id NUMBER NOT NULL, amount NUMBER(12,2));
CREATE TABLE SALES_TARGET (batch_id VARCHAR NOT NULL, order_id NUMBER NOT NULL, amount NUMBER(12,2) NOT NULL);
CREATE TABLE BATCH_AUDIT (
batch_id VARCHAR NOT NULL, attempt_no NUMBER NOT NULL, retry_of NUMBER,
started_at TIMESTAMP_LTZ NOT NULL, finished_at TIMESTAMP_LTZ NOT NULL,
source_cutoff TIMESTAMP_LTZ, status VARCHAR NOT NULL,
source_count NUMBER, target_count NUMBER, source_sales NUMBER(12,2),
target_sales NUMBER(12,2), error_detail VARCHAR
);
CREATE TABLE ALERT_OUTBOX (batch_id VARCHAR, alert_type VARCHAR, detected_at TIMESTAMP_LTZ);
CREATE TABLE DR_MARKERS (marker_id VARCHAR, written_at TIMESTAMP_LTZ);
INSERT INTO EXPECTED_BATCHES
SELECT 'B101', DATEADD('hour', 1, CURRENT_TIMESTAMP()), DATEADD('day', -1, CURRENT_TIMESTAMP()), 2
UNION ALL
SELECT 'B102', DATEADD('minute', -5, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), 2;
INSERT INTO SOURCE_ORDERS (batch_id, order_id, amount) VALUES
('B101', 701, 100.00), ('B101', 702, 50.00),
('B102', 703, 75.00), ('B102', 704, NULL);
SELECT batch_id, order_id, amount FROM SOURCE_ORDERS ORDER BY order_id;4–5 · Publish B101 and reconcile the target
The lab owner creates the procedure with CREATE PROCEDURE and owns the tables it touches. An authorized caller needs parent USAGE and USAGE on the procedure. EXECUTE AS OWNER runs its SQL with the owner’s access, so give USAGE only to the intended test operators. P_BATCH identifies the delivery. P_ATTEMPT identifies this run. P_RETRY_OF points to a prior attempt when one exists.
The procedure checks expected count, distinct order IDs and missing amounts before touching the target. The MERGE adds missing order IDs. The check compares both batch counts and the set of matching order keys with identical amounts. This catches an order already stored in a different batch or with an unexpected amount. This lab treats accepted orders as immutable. In a production model that accepts revisions, define version and correction rules first.
The publish and its PUBLISHED audit commit together. A failed statement rolls the write back and records an ERROR separately before re-raising. A rejected input writes its REJECTED audit before raising a clear error. REJECTED target_count is zero from this attempt because it wrote no target rows. The lab assumes one writer, unique attempt numbers and a stable source during each run. Standard Snowflake tables generally do not enforce unique audit keys. In production, enforce valid attempts in the orchestrator or through a suitable storage model.
- Expected batchPass to Incremental publish
- Expected batchFail to Rejection record
- Incremental publishReconcile and commit to Committed evidence
- Expected batch
- Check count, unique keys and amounts.
- Incremental publish
- MERGE only new keys for a valid batch.
- Committed evidence
- Commit verified target and success audit together.
- Rejection record
- Save the cause and fail the task before writing target rows.
CREATE PROCEDURE LS_M20_OPS_LAB.OPS.APPLY_SALES(
p_batch VARCHAR, p_attempt NUMBER, p_retry_of NUMBER
)
RETURNS VARCHAR
LANGUAGE SQL
EXECUTE AS OWNER
AS
$$
DECLARE
started_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP();
expected_count NUMBER;
expected_records NUMBER;
cutoff TIMESTAMP_LTZ;
source_rows NUMBER;
distinct_ids NUMBER;
missing_amounts NUMBER;
source_total NUMBER(12,2);
target_rows NUMBER;
matched_rows NUMBER;
target_total NUMBER(12,2);
attempts_used NUMBER;
failure_message VARCHAR;
bad_input EXCEPTION (-20020, 'Sales batch rejected. Read BATCH_AUDIT.');
bad_output EXCEPTION (-20021, 'Sales target did not reconcile.');
reused_attempt EXCEPTION (-20022, 'Use a new attempt number or inspect the existing audit row.');
BEGIN
SELECT COUNT(*) INTO :attempts_used
FROM LS_M20_OPS_LAB.OPS.BATCH_AUDIT WHERE batch_id = :p_batch AND attempt_no = :p_attempt;
IF (attempts_used > 0) THEN
RAISE reused_attempt;
END IF;
SELECT COUNT(*), MAX(expected_rows), MAX(source_cutoff)
INTO :expected_records, :expected_count, :cutoff
FROM LS_M20_OPS_LAB.OPS.EXPECTED_BATCHES WHERE batch_id = :p_batch;
SELECT COUNT(*), COUNT(DISTINCT order_id), COALESCE(COUNT_IF(amount IS NULL), 0), SUM(amount)
INTO :source_rows, :distinct_ids, :missing_amounts, :source_total
FROM LS_M20_OPS_LAB.OPS.SOURCE_ORDERS WHERE batch_id = :p_batch;
IF (expected_records <> 1 OR source_rows <> expected_count OR source_rows <> distinct_ids OR missing_amounts > 0) THEN
failure_message := CASE
WHEN expected_records <> 1 THEN 'Missing or duplicate delivery expectation'
WHEN source_rows <> expected_count THEN 'Unexpected source row count'
WHEN source_rows <> distinct_ids THEN 'Duplicate order ID'
ELSE 'Missing amount'
END;
BEGIN TRANSACTION;
INSERT INTO LS_M20_OPS_LAB.OPS.BATCH_AUDIT
VALUES (:p_batch, :p_attempt, :p_retry_of, :started_at, CURRENT_TIMESTAMP(),
:cutoff, 'REJECTED', :source_rows, 0, :source_total, NULL, :failure_message);
COMMIT;
RAISE bad_input;
END IF;
BEGIN
BEGIN TRANSACTION;
MERGE INTO LS_M20_OPS_LAB.OPS.SALES_TARGET AS t
USING (SELECT batch_id, order_id, amount FROM LS_M20_OPS_LAB.OPS.SOURCE_ORDERS
WHERE batch_id = :p_batch) AS s
ON t.order_id = s.order_id
WHEN NOT MATCHED THEN
INSERT (batch_id, order_id, amount) VALUES (s.batch_id, s.order_id, s.amount);
SELECT COUNT(*), SUM(amount) INTO :target_rows, :target_total
FROM LS_M20_OPS_LAB.OPS.SALES_TARGET WHERE batch_id = :p_batch;
SELECT COUNT(DISTINCT t.order_id) INTO :matched_rows
FROM LS_M20_OPS_LAB.OPS.SALES_TARGET AS t
INNER JOIN LS_M20_OPS_LAB.OPS.SOURCE_ORDERS AS s
ON t.batch_id = s.batch_id AND t.order_id = s.order_id AND t.amount = s.amount
WHERE t.batch_id = :p_batch;
IF (source_rows <> target_rows OR source_rows <> matched_rows) THEN
RAISE bad_output;
END IF;
INSERT INTO LS_M20_OPS_LAB.OPS.BATCH_AUDIT
VALUES (:p_batch, :p_attempt, :p_retry_of, :started_at, CURRENT_TIMESTAMP(),
:cutoff, 'PUBLISHED', :source_rows, :target_rows,
:source_total, :target_total, NULL);
COMMIT;
EXCEPTION
WHEN OTHER THEN
failure_message := 'Publish step SQL code: ' || TO_VARCHAR(SQLCODE);
ROLLBACK;
BEGIN TRANSACTION;
INSERT INTO LS_M20_OPS_LAB.OPS.BATCH_AUDIT
VALUES (:p_batch, :p_attempt, :p_retry_of, :started_at, CURRENT_TIMESTAMP(),
:cutoff, 'ERROR', :source_rows, NULL, :source_total, NULL, :failure_message);
COMMIT;
RAISE;
END;
RETURN 'PUBLISHED ' || p_batch;
END;
$$;Run the first batch and inspect the result
Call B101 before its fixture due time. NULL means there is no earlier attempt. The result proves two new orders were published.
| Orders | Total sales | Audit |
|---|---|---|
| 2 | 150.00 | B101 / 1 / PUBLISHED / 2 source / 2 target |
CALL LS_M20_OPS_LAB.OPS.APPLY_SALES('B101', 1, NULL);
SELECT COUNT(*) AS orders, SUM(amount) AS sales FROM LS_M20_OPS_LAB.OPS.SALES_TARGET;
SELECT batch_id, attempt_no, status, source_count, target_count
FROM LS_M20_OPS_LAB.OPS.BATCH_AUDIT ORDER BY batch_id, attempt_no;6–7 · Detect late delivery and prepare a supported notification
Use the dashboard query linked below to compare deadlines and actual publication. Before the failed task, the lab already shows B102 as MISSING when it is past due. No audit row is needed to show absence. B101 shows ON_TIME if published before its fixture cutoff. Choose a delivery check based on the audit and expected rows because native history does not know when the department needed the report.
Follow the scheduled alert setup as the lab alert owner. Execute it once and wait for its result, then repeat to check that the outbox still has one B102 delivery case. Use the new-data alert as a separate experiment if you want an immediate rejection signal. Use the approved email or cloud destination instructions only in a test account with permission to send. When no destination is available, stop at the outbox and use the representative delivery history.
| Batch | Delivery state | Outbox |
|---|---|---|
| B101 | ON_TIME | No case |
| B102 | MISSING | One DELIVERY_LATE case |
Run the operational dashboard query →
8–11 · Trigger a controlled task failure and find its cause
Create an unscheduled, standalone warehouse-backed task in the scratch schema. This task deliberately runs B102 attempt 1. EXECUTE TASK runs it once even when the root task is suspended. Keep it unscheduled and do not run again with the same attempt number. The task uses the task owner’s permissions, including access to call the procedure.
Wait for the run to finish. An immediate TASK_HISTORY query can show SCHEDULED or EXECUTING. Capture the FAILED row’s real query ID and then read the matching visible query history result. If the query ID is missing from the lookup, check monitoring privileges and widen or narrow the result window as appropriate. On a test account with a different failure, inspect the actual errors before using the repair below. A permission failure can happen before any audit row is written.
| Source | Expected evidence | Why it matters |
|---|---|---|
| Task and query history | FAILED · query ID q-maple-22 (illustration) · error says batch rejected | The orchestration reached the procedure and got an error. |
| Audit | B102 · attempt 1 · REJECTED · Missing amount | The audit was committed before raising the controlled exception. |
| Raw source | Order 704 has a NULL amount | This is the offending row. |
| Sales target | 2 orders, total 150.00 | The failed batch did not publish. |
CREATE TASK LS_M20_OPS_LAB.OPS.SALES_TASK
WAREHOUSE = MAPLE_WH
AS CALL LS_M20_OPS_LAB.OPS.APPLY_SALES('B102', 1, NULL);
EXECUTE TASK LS_M20_OPS_LAB.OPS.SALES_TASK;
-- Run after the task finishes. Check the exact batch attempt before patching.
WITH recent_task AS (
SELECT name, state, error_message, query_id
FROM TABLE(LS_M20_OPS_LAB.INFORMATION_SCHEMA.TASK_HISTORY(
TASK_NAME => 'SALES_TASK',
SCHEDULED_TIME_RANGE_START => DATEADD('hour', -1, CURRENT_TIMESTAMP())
))
WHERE database_name = 'LS_M20_OPS_LAB' AND schema_name = 'OPS'
),
recent_query AS (
SELECT query_id, execution_status, error_code
FROM TABLE(LS_M20_OPS_LAB.INFORMATION_SCHEMA.QUERY_HISTORY(
END_TIME_RANGE_START => DATEADD('hour', -1, CURRENT_TIMESTAMP()),
RESULT_LIMIT => 1000
))
)
SELECT t.name, t.state, t.query_id, t.error_message, q.error_code
FROM recent_task AS t LEFT JOIN recent_query AS q ON t.query_id = q.query_id;
SELECT batch_id, attempt_no, status, error_detail
FROM LS_M20_OPS_LAB.OPS.BATCH_AUDIT WHERE batch_id = 'B102';
SELECT order_id FROM LS_M20_OPS_LAB.OPS.SOURCE_ORDERS
WHERE batch_id = 'B102' AND amount IS NULL;12–14 · Correct the source, retry and prove replay is safe
The source owner confirms that order 704 should be 25.00. As the authorized lab writer, patch only that order in this fictional raw table. Real pipelines should retain the original input and record the approved correction or load a corrected source delivery. Send a new attempt number and link to attempt 1.
After the retry, compare target keys, batch totals and audit. Run another attempt with the same corrected input to prove the target does not change. The MERGE matches all previously written order IDs and inserts nothing. The successful replay adds an audit row but no sales. If the new test returns an error, inspect mismatch, permissions and prior attempts before rerunning.
| Checkpoint | Order IDs | Orders | Sales |
|---|---|---|---|
| B101 committed | 701, 702 | 2 | 150.00 |
| B102 rejected | 701, 702 | 2 | 150.00 |
| B102 retry committed | 701, 702, 703, 704 | 4 | 250.00 |
| B102 replay committed | 701, 702, 703, 704 | 4 | 250.00 |
UPDATE LS_M20_OPS_LAB.OPS.SOURCE_ORDERS SET amount = 25.00
WHERE batch_id = 'B102' AND order_id = 704 AND amount IS NULL;
CALL LS_M20_OPS_LAB.OPS.APPLY_SALES('B102', 2, 1);
SELECT batch_id, order_id, amount FROM LS_M20_OPS_LAB.OPS.SALES_TARGET ORDER BY order_id;
CALL LS_M20_OPS_LAB.OPS.APPLY_SALES('B102', 3, 2);
SELECT COUNT(*) AS orders, COUNT(DISTINCT order_id) AS distinct_orders, SUM(amount) AS sales
FROM LS_M20_OPS_LAB.OPS.SALES_TARGET;
SELECT batch_id, attempt_no, retry_of, status, source_count, target_count, target_sales
FROM LS_M20_OPS_LAB.OPS.BATCH_AUDIT ORDER BY batch_id, attempt_no;Compare attempt records and close the incident
B102’s first attempt has a NULL target amount because it never tried a write. Its source total of 75.00 is incomplete because SUM skips NULL. The count and missing-amount check explain why the batch was rejected. Attempts 2 and 3 each verify the same two B102 rows for 100.00. The total of 250.00 includes B101’s 150.00. Mark the outbox case resolved after verification, without erasing the missed deadline.
| Attempt | Retry of | Status | Source rows | Target rows | Verified batch total |
|---|---|---|---|---|---|
| 1 | NULL | REJECTED | 2 | 0 | NULL |
| 2 | 1 | PUBLISHED | 2 | 2 | 100.00 |
| 3 | 2 | PUBLISHED | 2 | 2 | 100.00 |
15–19 · Rehearse a documented secondary-account recovery
If you have no second authorized test account, do the entire recovery as a tabletop exercise using the sample evidence below. For a live rehearsal, use two replication-enabled test accounts of the eligible edition and approved test operators. Create the primary failover group in MAPLE_EAST and its replica in MAPLE_WEST. Confirm the latest completed refresh and a readable copy. Then follow the linked runbook for fencing writers, final refresh, promotion and client validation. Use those exact role and account checkpoints to avoid switching live users.
After the switch, read the counts, sums and B102 audit from the test application’s new session. Insert the controlled recovery marker once using the test writer. Measure across the whole service path. In the simulated clock, 09:00 minus 08:53 is a seven-minute recoverable gap and 09:16 minus 09:00 is sixteen minutes of downtime. Both meet the example targets. A completed database command at 09:10 would only prove one recovery step.
| UTC | Evidence |
|---|---|
| 08:53 | Last recoverable source snapshot contains four orders and B102 publication |
| 09:00 | Service unavailable in MAPLE_EAST |
| 09:10 | MAPLE_WEST group promoted |
| 09:16 | Application on MAPLE_WEST reads 4 / 250 and confirms a controlled write |
Configure and verify the secondary group →
20 · Document ownership, evidence and cleanup
The source owner prevents missing sales amounts and confirms any authorized correction. The pipeline owner owns audit and replay, and the on-call responder owns incident updates and the alert heartbeat. The recovery lead approves failover and signs off with the client and data owners. Record remaining gaps, time stamps, last verified counters, responder names and due dates.
Keep the evidence before cleanup. The alert and task owners suspend any scheduled lab objects. Remove the optional test notification integration only if it was created for this exercise and no one uses it. If you built a replica, follow the group and connection cleanup in the runbook before removing the scratch database. The authorized owner can then drop the single-use scratch database in a test account. Keep the shared approved warehouse.
Interview practice
Explain the decision and the evidence you would use to test it.
Beginner · Why do you need both task history and a batch audit?
Task history tells me what Snowflake ran. The audit tells me which orders were expected and whether the verified result was published. I need both to distinguish a processing error from a delivery gap.
SQL · How do you show a retry is idempotent?
I repeat the same corrected batch with a new attempt number and confirm order keys, counts and amounts are unchanged. I keep both attempt records.
Production · Who decides whether failover is safe?
An incident lead decides using data and application evidence. The Snowflake operator confirms the replica and controlled writers, the client owner tests the new connection, and the data owner signs off on the recovered cut of data.
Words used in this lesson
- Idempotent
- Running the same accepted business batch again leaves the same business result.
- Atomic publish
- The target write and the successful audit commit together, or neither is committed.
- Recovery marker
- A known committed value that helps prove the copy contains an expected write.
- Fictional clock
- The representative incident timeline. Live scratch runs use actual timestamps.
Try the SQL or command
Read → predict → run in your learning environment → compare. You can also learn by reading without an account.
Use the SQL and expected outputs in the sections above.
New to SQL? Where to run it and how to read it
A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.
- No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
- For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
- Read the entire example, including comments beginning with
--. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor. - Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
- SELECT / FROM
- Choose the values to return / identify their input.
- VALUES / COLUMN1
- VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
- AS / WITH
- AS gives a result a readable name. WITH names a temporary query step within one statement.
- NULL / ::
- NULL means missing or unknown. The :: notation converts a value to a named data type.
- Session
- One connection and its settings. Keep related transaction steps in the same session.
- Database.schema.table
- A full address for stored data. It is separate from the warehouse that processes queries.
Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →
Help with common practice errors
- No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
- Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
- Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
- Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.
Before running this lesson
Maple Market is fictional. Output tables are representative. Live commands require an authorized test account and the roles, compute and edition listed in each lesson.
Check your understanding
Choose an answer, then check your reasoning. This is practice, not a scored test.
Try it yourself
After the recovery switch, all four orders are visible but the write marker failed. What is your next step?
Compare your reasoning
Keep general writers paused and the recovery clock running. Check the actual account and region, the group primary status, and application role grants. Restart traffic only after the agreed read and write checks succeed.
Connect this lesson to the learning path
Official sources and curriculum
Module 20 · See module scope
By Rohit Ray · Independent educational lesson · Explore this visual lab